Symfony2: How to properly include assets in conjunction with Twig template inheritance?

余生长醉 提交于 2019-12-03 13:47:17

Using assetic would address all your issues.

I hear that this is not possible if you include stylesheets at different levels, i.e. it wouldn't work with the three-level inheritance system

You can, but it will generate a css file for each level (just like with asset(), actually).

Example:

layout:

{% block stylesheets %}
    {{ parent() }}
    {% stylesheets 'main.css' %}
        <link rel="stylesheet" type="text/css" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

sub-template:

{% block stylesheets %}
    {{ parent() }}
    {% stylesheets 'sub.css' %}
        <link rel="stylesheet" type="text/css" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

result:

<link rel="stylesheet" type="text/css" href="..." />
<link rel="stylesheet" type="text/css" href="..." />

Alternatively sub-template can completly override the stylesheets block, so that only one stylesheet is generated (but it's less dry):

{% block stylesheets %}
    {% stylesheets 'main.css' 'sub.css' %}
        <link rel="stylesheet" type="text/css" href="{{ asset_url }}" />
    {% endstylesheets %}
{% endblock %}

result (in production / non debug):

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