Symfony2: How to share js libs and css between bundles

梦想与她 提交于 2019-11-27 03:44:42

问题


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...


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/11192568/symfony2-how-to-share-js-libs-and-css-between-bundles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!