Skip to content
Whether you think you can
or think you can’t, you’re right
Henry Ford

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: 📒 Nunjucks scoped variable declarations

Edit this page on GitHub

Comment on DEV.to or Hashnode

Take me to the next post!