DEV Community

loading...

Nunjucks scoped variable declarations

Giulia Chiola
Front-end Developer. 👾 Media engineer. ⚡ Facing life one bug at a time. 🔥 Easily bribed with chocolate. 🍫 she/her.
Originally published at giuliachiola.dev ・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 #}
Enter fullscreen mode Exit fullscreen mode
{% 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) #}
Enter fullscreen mode Exit fullscreen mode

📚 More info

Twig docs - set variables

Discussion (0)

Forem Open with the Forem app