DEV Community

Giulia Chiola
Giulia Chiola

Posted on • Originally published at giuliachiola.dev

Nunjucks scoped variable declarations

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

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere “thank you” often brightens someone’s day—share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay