Symfony2: How to share js libs and css between bun

2019-01-18 15:40发布

I have different Bundles: MainBundle (Homepage), SecurityBundle (Login, Registration), MessageBundle (Message System), ShopBundle.

I also follow the three stage layout schema (::base.html.twig, AcmeMainBundle::layout.html.twig, AcmeMainBundle:Default:index.html.twig).

But I have problems sharing common js libaries through the application (e.g. jquery) and defining a base.css (which sets some base classes, backgrounds, fonts etc.)

So whats the best approach to use shared css and js withouth having to lose assetic support?

One idea would be to create a CommonBundle which holds all global js and css and some layout files but I don't think this is the best way to handle this...

2条回答
手持菜刀,她持情操
2楼-- · 2019-01-18 16:10

Using a recent version of Symfony (2.5) I have seen that the fsenart's response did not work in my case. Instead I put the public folder with the shared content into the web folder :

web/public
  --js
  --css

Then to use it in the main layout the following code works :

{% block javascripts %}
    {% javascripts 'public/js/*' %}
        <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

But for this to work to not forget to call the Twig parent() function when using the javascript block in a child layout.

查看更多
够拽才男人
3楼-- · 2019-01-18 16:19

If you want to share common assets among all your bundles, the best choice is to place them in the app/Resources/public directory. For example:

app/Resources/Public
|-- css
|   `-- base.css
|-- js
|   `-- jquery.js

Then you can reference them in your layout as follow:

{% block stylesheets %}
  {% stylesheets '../app/Resources/public/css/*' %}
    <link rel="stylesheet" type="text/css" charset="UTF-8" media="all" href="{{ asset_url }}"/>
  {% endstylesheets %}
{% endblock %}

{% block javascripts %}
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  {% javascripts '../app/Resources/public/js/*' %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
  {% endjavascripts %}
{% endblock %}

Remark: As you can see, for common libraries like jQuery, the best choice remains the use of common cached version hosted at Google. This kind of practice can speedup your application response time.

查看更多
登录 后发表回答