1

I would like to load some javascript on specific pages only.

I'm trying to set a block in my parent template, then test a variable and include the javascript in the child template only when necessary.

I thought I could do this by declaring the variable beforehand, to make it accessible outside it's scope, but this is not working (nothing is returned):

Parent '_layout' template:

<html>
    <head>...</head>
    <body>

        {% block content %}
        {% endblock %}

        ...

        {# site-wide script #}
        <script src="global.js"></script>

        {# page-specific script #}
        {% block script %}
        {% endblock %}

    </body>
</html>

Child template:

{% extends "_layout" %}

{% set page_assets = '' %}

{% block content %}
...
{% set page_assets = 'true' %}
...
{% endblock %}

{% block script %}
    {% if page_assets is defined and page_assets is not empty %}
      <script src="page-specific.js"></script>
    {% endif %}
{% endblock %}
1

Nope, that's not going to work unfortunately, due to the way scoping works in Twig. Check out the explanation in the Twig Processing Order & Scope article

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.