Nunjucks scoped variable declarations

ยท

1 min read

We have to pay attention where we set Nunjucks variables because they are scoped

{% set animals = ['๐Ÿฑ', '๐Ÿถ', '๐Ÿบ'] %}

{% for item in animals %}
  {% set animal = item %}
{% endfor %}

{{ animal }}
{# animal -> ERROR #}
{# animal declared INSIDE the loop is NOT available #}
{% set animals = ['๐Ÿฑ', '๐Ÿถ', '๐Ÿบ'] %}

{# note this declaration #}
{% set animal = '' %}

{% for item in animals %}
  {% set animal = item %}
{% endfor %}

{{ animal }}
{# animal declared OUTSIDE the loop is available #}
{# animal -> ๐Ÿบ (last array item) #}

๐Ÿ“š More info

Twig docs - set variables