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

Forem Open with the Forem app