从包含的 Twig 模板中干净地添加 JS 和 CSS [英] Adding JS and CSS cleanly from included Twig templates

查看:17
本文介绍了从包含的 Twig 模板中干净地添加 JS 和 CSS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一种干净的方法可以从包含的模板中添加 JS 和 CSS.

I'm looking to find out if there's a clean way to add JS and CSS from included templates.

例如,如果 layout.html.twig 有:

So, for example, if layout.html.twig has:

{% include 'GenericBundle:Generic:page.html.twig' with {'data': data} %}
...
{% block javascript %}

    {% javascripts
        '@GenericBundle/Resources/public/js/app/jquery/jquery.min.js'
        '@GenericBundle/Resources/public/js/lib/bootstrap/bootstrap.min.js'
    %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}

{% endblock %}

在通用包页面中,我想包含更多的 Javascript,但将其添加到已建立的 Javascript 块中以保持 HTML 和 JS 最佳实践.

And in the generic bundle page I'd like to include some more Javascript but add it to the established Javascript block to keep to HTML and JS best practices.

有没有干净的方法来做到这一点?我正在使用 Symfony2,并且可能会使用 Singletons 之类的方法拼凑出一个解决方案,但如果有可用的方法,我宁愿使用一种更简洁的方法.

Is there a clean way to do this? I'm using Symfony2, and could probably cludge together a solution using Singletons and such, but I'd rather a cleaner method if there's one available.

推荐答案

我知道我参加聚会有点晚了,但是使用 Twig 1.2,您可以利用 use 标签和 block 函数:

I know I'm a little late to the party, but with Twig 1.2, you can utilize the use tag and the block function:

GenericBundle:Generic:page.html.twig

{% block javascripts %}
    <script src="..."></script>
{% endblock %}
{% block included_content %}
   Bar
{% endblock %}

layout.html.twig

{% use 'GenericBundle:Generic:page.html.twig' with javascripts as page_javascripts %}

{% block javascript %}

    {% javascripts
        '@GenericBundle/Resources/public/js/app/jquery/jquery.min.js'
        '@GenericBundle/Resources/public/js/lib/bootstrap/bootstrap.min.js'
    %}
        <script src="{{ asset_url }}"></script>
    {% endjavascripts %}
    {{ block('page_javascript') }} // Don't forget the 'braces'

{% endblock %}

...
{{ block('included_content') }} // Don't forget the 'braces'

这篇关于从包含的 Twig 模板中干净地添加 JS 和 CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆