push
The push filter pushes a value to the end of an array. It can sometimes be simpler than using the merge filter.
{% set animals = [] %}
{% set animals = animals|push('dog') %}
{% set animals = animals|push('cat') %}
{% set animals = animals|push('fish') %}
{# animals is now ['dog', 'cat', 'fish'] #}
You can also set values with a specific array key. In that case the first parameter is the array key and the second value is the value to add to the array.
Note that if the array already contains a value at the array key that you are using then the existing value will be overwritten with your new value.
{% set obj = {} %}
{% set obj = obj|push('b', 'blue') %}
{% set obj = obj|push('r', 'red') %}
{% set obj = obj|push('y', 'yellow') %}
{% set obj = obj|push(3, 'number') %}
{% set obj = obj|push(2, 'number 2') %}
{# obj is now {'b': 'blue', 'r': 'red', 'y': 'yellow', 3: 'number', 2: 'number 2'} #}
Arguments
The push filter has the following signature.
push(key, value)
Argument | Description |
---|---|
key | If you are setting a value in the array with a specific array key then this would be that array key. However, if you are just adding a value to a numeric array then you can set the value in the first parameter and leave off the second parameter. Set just the value. The array key of the new value will be numeric. {% set animals = animals|push('dog') %} Set a value with a specific array key {% set manufacturers = manufacturers|push('Toyota', 'Rav4') %} {% set dates = dates|push(1555606629, dataForToday) %} |
value | If you are setting a value in the array with a specific array key then pass the value as the second parameter. {% set manufacturers = manufacturers|push('Toyota', 'Rav4') %} {% set dates = dates|push(1555606629, dataForToday) %} Leave this parameter out if you are simply adding a value to a numeric-keyed array. {% set animals = animals|push('dog') %} Note that if the array already contains a value at the array key that you are using then the existing value will be overwritten with your new value. |