DEV Community

loading...

Add items to an array in Nunjucks

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

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 (2)

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