With Assetic / Twig / Symfony2, can I define front end libraries?

你说的曾经没有我的故事 提交于 2019-11-27 12:15:33

Although there is indeed support for defining front-end libraries, there is unfortunately no support for dependency resolving. You must also define your CSS and JavaScript separately.

What I have been doing, is creating a separate file in /app/config/ called assets.yml and including it in the main configuration to keep things clean.

assetic:
    assets:
        jquery:
            inputs:
                - '%kernel.root_dir%/Resources/public/js/jquery.js'
                - '%kernel.root_dir%/Resources/public/js/jquery-ui.js'
        my_lib:
            inputs:
                - '%kernel.root_dir%/Resources/public/js/my-custom-lib.js'
                - ...

Note that ´%kernel.root_dir%´ resolves to the app directory by default in Symfony2. You may now use the assets in your Twig templates.

{% block javascripts %}
    {% javascripts '@jquery' '@my_lib' output="js/jquery.js" %}
        <script type="text/javascript" src="{{ asset_url }}"></script>
    {% endjavascripts %}
{% endblock %}

The same could be done for CSS files. The example also demonstrates why it's not possible to define CSS and JavaScript as a single asset.

The simplest solution is to put them in appropriate directories in the web/ directory as this is the root of your site that is served for all your Symfony bundles.

You might want to check out Cartero, which allows you to define "asset bundles", including dependencies, and then include those bundles in your page.

https://github.com/rotundasoftware/cartero

You would need to write a Symfony2 Hook, but that wouldn't be too difficult.

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