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 ๐คท๐ปโโ๏ธ
Top comments (12)
Thanx for inspiration!
I've ended up with the following:
Result in output:
I din't know the reject() method! Thanks for sharing Pavel!
Instead of
push
useconcat
, it will simplify things a bit:Thanks for sharing Felipe! I didn't know about the
concact()
method. I've just checked the official Mozilla blog, and they wrote only about join() for concatenate string. Thanks for make me discovering it!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']).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? ๐ค
hey Vadim, thank you for your feedback! I just added at the end of the post where I found the
push
ย syntax ๐ I can't really tell why this filter is not available on the official docs.Exactly what I was looking for. Worked like a charm !
Thank you !
I'm glad it was helpful! ๐ช๐ป Thank you
This is very useful - thanks
I'm glad that it has been helpful to you. ๐
is there a similar filter to add additional key/value properties in an object?