Filters: Arrays and Collections
Filters
length
String length or collection size:
length
{{ 'hello'|length }}
{# 5 #}
{{ users|length }}
first / last
First or last element:
first / last
{{ [1, 2, 3]|first }}
{# 1 #}
{{ [1, 2, 3]|last }}
{# 3 #}
{{ 'hello'|first }}
{# h #}
keys
Array keys:
keys
{% for key in data|keys %}
{{ key }}
{% endfor %}
join
Joins array elements into a string:
join
{{ ['a', 'b', 'c']|join(', ') }}
{# a, b, c #}
{{ users|map(u => u.name)|join(', ') }}
merge
Merges arrays or hashes:
merge
{% set combined = [1, 2]|merge([3, 4]) %}
{# [1, 2, 3, 4] #}
{% set config = defaults|merge({debug: true}) %}
batch
Splits an array into groups:
batch
{% for row in items|batch(3) %}
<div class="row">
{% for item in row %}
<div class="col">{{ item }}</div>
{% endfor %}
</div>
{% endfor %}
{% for row in items|batch(3, 'empty') %}
column
Extracts a column from an array:
column
{{ users|column('name') }}
{# ['John', 'Jane', 'Bob'] #}
{{ users|column('name', 'id') }}
{# {1: 'John', 2: 'Jane', 3: 'Bob'} #}
filter
Filters array elements:
filter
{{ numbers|filter(n => n > 3) }}
{{ users|filter(u => u.active) }}
find
Finds the first element matching a condition:
find
{{ users|find(u => u.name == 'John') }}
map
Transforms each element:
map
{{ users|map(u => u.name) }}
{# ['John', 'Jane'] #}
{{ numbers|map(n => n * 2) }}
reduce
Reduces an array to a single value:
reduce
{{ [1, 2, 3, 4]|reduce((carry, item) => carry + item, 0) }}
{# 10 #}
sort
Sorts an array:
sort
{{ [3, 1, 2]|sort }}
{# [1, 2, 3] #}
{{ users|sort((a, b) => a.name <=> b.name) }}
reverse
Reverses an array or string:
reverse
{{ [1, 2, 3]|reverse }}
{# [3, 2, 1] #}
{{ 'hello'|reverse }}
{# olleh #}
shuffle
Randomly shuffles an array:
shuffle
{{ [1, 2, 3, 4, 5]|shuffle }}
slice
Extracts a portion of an array or string:
slice
{{ [1, 2, 3, 4, 5]|slice(1, 3) }}
{# [2, 3, 4] #}
{{ 'hello'|slice(0, 3) }}
{# hel #}