<p>Nope, that's not going to work unfortunately, due to the way scoping works in Twig. Check out the explanation in the <a href="https://nystudio107.com/blog/twig-processing-order-and-scope" rel="nofollow noreferrer">Twig Processing Order &amp; Scope</a> article</p>

CC BY-SA 3.0
2017-04-14T14:18:42.323Z
2017-04-14T14:18:42.323Z
andrew.welch
<p>I would like to load some javascript on specific pages only.</p>

<p>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. </p>

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

<p>Parent '_layout' template:</p>

<pre><code>&lt;html&gt;
    &lt;head&gt;...&lt;/head&gt;
    &lt;body&gt;

        {% block content %}
        {% endblock %}

        ...

        {# site-wide script #}
        &lt;script src="global.js"&gt;&lt;/script&gt;

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

    &lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>Child template:</p>

<pre><code>{% 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 %}
      &lt;script src="page-specific.js"&gt;&lt;/script&gt;
    {% endif %}
{% endblock %}
</code></pre>

<scope>
How to set and test a variable in child template to modify a block in parent template
# How to set and test a variable in child template to modify a block in parent template

(Asked by: username_0 on 2017-04-13)

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:

    ...
    

        {% block content %}
        {% endblock %}

        ...

        {# site-wide script #}
        

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

    


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 %}
      
    {% endif %}
{% endblock %}

**Tags:** scope

---

## 1 answers

### Answer by username_1 on 2017-04-14. Score: 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](https://nystudio107.com/blog/twig-processing-order-and-scope) article


---

