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: 📒 Nunjucks scoped variable declarations
📚 More info
Docs about Twig 'push' filter. Note that this filter is not present into the official Twig documentation 🤷🏻♀️