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
Discussion (4)
Thank you! I had no idea that you can execute arbitrary JS right in the tags.
Do you know where I can read more about that? Youβre not just reassigning the value with the pushed item, itβs also wrapped in brackets and you repeat arrayβs name after a comma. Where this comes from? π€
It is a great post. though I am stuck at a point where I need to pass this final array to another statement such as:
window.master.init({{domesticAnimals}});
. this showswindow.master.init(cat,dog);
instead of array. what should I do to pass an array in the above statement. I need data like `window.master.init(['cat','dog']).Exactly what I was looking for. Worked like a charm !
Thank you !
I'm glad it was helpful! πͺπ» Thank you