Adding JS and CSS cleanly from included Twig templates

57,869

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'
Share:
57,869
Andrew Stirling
Author by

Andrew Stirling

Updated on April 09, 2020

Comments

  • Andrew Stirling
    Andrew Stirling about 4 years

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

    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 %}
    

    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.

    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.

  • Vincent Pazeller
    Vincent Pazeller over 10 years
    You must put quotes in {{ block('page_javascript') }} for this to work, otherwise you get a "Variable ... does not exists..." error message
  • webDEVILopers
    webDEVILopers over 9 years
    {% include ... with { javascripts: block('javascripts') } %} worked fine for me.