Add items to an array in Nunjucks

ยท

1 min read

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

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

Final array:

arr = [1,2,3]

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 %}

Final array:

domesticAnimals = ['cat ๐Ÿฑ', 'dog ๐Ÿถ']

๐Ÿงจ !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


๐Ÿ“š More info

Docs about Twig 'push' filter. Note that this filter is not present into the official Twig documentation ๐Ÿคท๐Ÿปโ€โ™€๏ธ