Skip to main content

Command Palette

Search for a command to run...

Add items to an array in Nunjucks

Updated
โ€ข1 min read
G

Front-end Developer. ๐Ÿ‘พ Media engineer. โšก Facing life one bug at a time. ๐Ÿ”ฅ Easily bribed with chocolate. ๐Ÿซ she/her - #BLM

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 ๐Ÿคท๐Ÿปโ€โ™€๏ธ

M

TY. Found this after trying to accomplish this exact same feature. This is really useful.

1
G

Glad this post was useful! ๐Ÿ˜Š

More from this blog

Giulia Chiola's Blog

30 posts

Front-end Developer. ๐Ÿ‘พ Media engineer. โšก

Facing life one bug at a time. ๐Ÿ”ฅ Easily bribed with chocolate. ๐Ÿซ she/her