DEV Community

Giulia Chiola
Giulia Chiola

Posted on • Originally published at giuliachiola.dev

Add items to an array in Nunjucks

To add items in Nunjucks, use the .push() function.

  {% set arr = [1,2] %}
  {% set arr = (arr.push(3), arr) %}
Enter fullscreen mode Exit fullscreen mode

Final array:

arr = [1,2,3]
Enter fullscreen mode Exit fullscreen mode

Unfortunately, I did not found any references in the official Nunjucks documentation for this useful function 🤷🏻‍♀️

  {% set animals = ['cat 🐱', 'dog 🐶', 'lion 🦁'] %}
  {% set domesticAnimals = [] %}
  {% for animal in animals %}
    {% if animal !== 'lion' %}
      {% set domesticAnimals = (domesticAnimals.push(animal), domesticAnimals) %}
    {% endif %}
  {% endfor %}
Enter fullscreen mode Exit fullscreen mode

Final array:

domesticAnimals = ['cat 🐱', 'dog 🐶']
Enter fullscreen mode Exit fullscreen mode

🧨 !important

If you use {% set .... %} inside a for-loop block, pay attention to have defined it outside before entering the loop.
I wrote a post about it: 📒 Nunjuks scoped variable declarations

Discussion (3)

Collapse
dhara profile image
BDhara • Edited on

It is a great post. though I am stuck at a point where I need to pass this final array to another statement such as: window.master.init({{domesticAnimals}});. this shows window.master.init(cat,dog); instead of array. what should I do to pass an array in the above statement. I need data like `window.master.init(['cat','dog']).

Collapse
sueharaluke profile image
Lucas Suehara Emilio

Exactly what I was looking for. Worked like a charm !

Thank you !

Collapse
giulia_chiola profile image
Giulia Chiola Author

I'm glad it was helpful! 💪🏻 Thank you