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) %}
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 ๐คท๐ปโโ๏ธ