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
Top comments (0)