1abs
The abs filter returns the absolute value.
{# number = -5 #}
{{ number|abs }}
{# outputs 5 #}
2batch
The batch filter "batches" items by returning a list of lists with the given number of items. A second parameter can be provided and used to fill in missing items
See doc for examples.
3capitalize
The capitalize filter capitalizes a value. The first character will be uppercase, all others lowercase:
{{ 'my first car'|capitalize }}
{# outputs 'My first car' #}
4column
The column filter returns the values from a single column in the input array.
{% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}
{% set fruits = items|column('fruit') %}
{# fruits now contains ['apple', 'orange'] #}
5date
The date filter formats a date to a given format:
{{ post.published_at|date("m/d/Y") }}
6default
The default filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable:
{{ var|default('var is not defined') }}
7date_modify
The date_modify filter modifies a date with a given modifier string:
{{ post.published_at|date_modify("+1 day")|date("m/d/Y") }}
The date_modify filter accepts strings (it must be in a format supported by the strtotime function) or DateTime instances. You can combine it with the date filter for formatting.
8escape
The escape filter escapes a string using strategies that depend on the context.
By default, it uses the HTML escaping strategy:
{{ user.username|escape }}
For convenience, the e filter is defined as an alias:
{{ user.username|e }}
9filter
The filter filter filters elements of a sequence or a mapping using an arrow function. The arrow function receives the value of the sequence or mapping:
{% set sizes = [34, 36, 38, 40, 42] %}
{{ sizes|filter(v => v > 38)|join(', ') }}
{# output 40, 42 #}
Combined with the for tag, it allows to filter the items to iterate over:
{% for v in sizes|filter(v => v > 38) -%}
{{ v }}
{% endfor %}
{# output 40 42 #}
10first
The first filter returns the first "element" of a sequence, a mapping, or a string:
{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}
{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}
{{ '1234'|first }}
{# outputs 1 #}
11format
The format filter formats a given string by replacing the placeholders (placeholders follows the sprintf notation):
{{ "I like %s and %s."|format(foo, "bar") }}
{# outputs I like foo and bar
if the foo parameter equals to the foo string. #}
12json_encode
The json_encode filter returns the JSON representation of a value:
{{ data|json_encode() }}
13keys
The keys filter returns the keys of an array. It is useful when you want to iterate over the keys of an array:
{% for key in array|keys %}
...
{% endfor %}
14last
The last filter returns the last "element" of a sequence, a mapping, or a string:
{{ [1, 2, 3, 4]|last }}
{# outputs 4 #}
{{ { a: 1, b: 2, c: 3, d: 4 }|last }}
{# outputs 4 #}
{{ '1234'|last }}
{# outputs 4 #}
15length
The length filter returns the number of items of a sequence or mapping, or the length of a string.
For objects that implement the Countable interface, length will use the return value of the count() method.
For objects that implement the __toString() magic method (and not Countable), it will return the length of the string provided by that method.
For objects that implement the Traversable interface, length will use the return value of the iterator_count() method.
For strings, mb_strlen() is used.
{% if users|length > 10 %}
...
{% endif %}
16lower
The lower filter converts a value to lowercase:
{{ 'WELCOME'|lower }}
{# outputs 'welcome' #}
17map
The map filter applies an arrow function to the elements of a sequence or a mapping. The arrow function receives the value of the sequence or mapping:
{% set people = [
{first: "Bob", last: "Smith"},
{first: "Alice", last: "Dupond"},
] %}
{{ people|map(p => "#{p.first} #{p.last}")|join(', ') }}
{# outputs Bob Smith, Alice Dupond #}
The arrow function also receives the key as a second argument:
{% set people = {
"Bob": "Smith",
"Alice": "Dupond",
} %}
{{ people|map((value, key) => "#{key} #{value}")|join(', ') }}
{# outputs Bob Smith, Alice Dupond #}
Note that the arrow function has access to the current context.
18merge
The merge filter merges an array with another array:
{% set values = [1, 2] %}
{% set values = values|merge(['apple', 'orange']) %}
{# values now contains [1, 2, 'apple', 'orange'] #}
New values are added at the end of the existing ones.
The merge filter also works on hashes:
{% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}
{% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %}
{# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car' } #}
For hashes, the merging process occurs on the keys: if the key does not already exist, it is added but if the key already exists, its value is overridden.
19nl2br
The nl2br filter inserts HTML line breaks before all newlines in a string:
{{ "I like Twig.\nYou will like it too."|nl2br }}
{# outputs
I like Twig.<br />
You will like it too.
#}
20number_format
The number_format filter formats numbers. It is a wrapper around PHP's number_format function
21raw
The raw filter marks the value as being "safe", which means that in an environment with automatic escaping enabled this variable will not be escaped if raw is the last filter applied to it:
{% autoescape %}
{{ var|raw }} {# var won't be escaped #}
{% endautoescape %}
22reduce
The reduce filter iteratively reduces a sequence or a mapping to a single value using an arrow function, so as to reduce it to a single value. The arrow function receives the return value of the previous iteration and the current value and key of the sequence or mapping:
{% set numbers = [1, 2, 3] %}
{{ numbers|reduce((carry, v, k) => carry + v * k) }}
{# output 8 = (1*2) + (2*3) #}
The reduce filter takes an initial value as a second argument:
{{ numbers|reduce((carry, v, k) => carry + v * k, 10) }}
{# output 18 = 10 + (1*2) + (2*3)#}
Note that the arrow function has access to the current context.
23replace
The replace filter replaces placeholders in a string (the placeholder format is free-form):
{{ "I like %this% and %that%."|replace({'%this%': fruit, '%that%': "oranges"}) }}
{# if the "fruit" variable is set to "apples", #}
{# it outputs "I like apples and oranges" #}
{# using % as a delimiter is purely conventional and optional #}
{{ "I like this and --that--."|replace({'this': fruit, '--that--': "oranges"}) }}
{# outputs "I like apples and oranges" #}
24round
The round filter rounds a number to a given precision:
{{ 42.55|round }}
{# outputs 43 #}
{{ 42.55|round(1, 'floor') }}
{# outputs 42.5 #}
The round filter takes two optional arguments; the first one specifies the precision (default is 0) and the second the rounding method (default is common):
common rounds either up or down (rounds the value up to precision decimal places away from zero, when it is half way there -- making 1.5 into 2 and -1.5 into -2);
ceil always rounds up;
floor always rounds down.
25slice
The slice filter extracts a slice of a sequence, a mapping, or a string:
{% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
{# will iterate over 2 and 3 #}
{% endfor %}
{{ '12345'|slice(1, 2) }}
{# outputs 23 #}
26sort
The sort filter sorts an array:
{% for user in users|sort %}
...
{% endfor %}
Note
Internally, Twig uses the PHP asort function to maintain index association. It supports Traversable objects by transforming those to arrays.
You can pass an arrow function to sort the array:
{% set fruits = [
{ name: 'Apples', quantity: 5 },
{ name: 'Oranges', quantity: 2 },
{ name: 'Grapes', quantity: 4 },
] %}
{% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
{{ fruit }}
{% endfor %}
{# output in this order: Oranges, Grapes, Apples #}
Note the usage of the spaceship operator to simplify the comparison.
27spaceless
Use the spaceless filter to remove whitespace between HTML tags, not whitespace within HTML tags or whitespace in plain text:
{{
"<div>
<strong>foo</strong>
</div>
"|spaceless }}
{# output will be <div><strong>foo</strong></div> #}
You can combine spaceless with the apply tag to apply the transformation on large amounts of HTML:
{% apply spaceless %}
<div>
<strong>foo</strong>
</div>
{% endapply %}
{# output will be <div><strong>foo</strong></div> #}
This tag is not meant to "optimize" the size of the generated HTML content but merely to avoid extra whitespace between HTML tags to avoid browser rendering quirks under some circumstances.
28split
The split filter splits a string by the given delimiter and returns a list of strings:
{% set foo = "one,two,three"|split(',') %}
{# foo contains ['one', 'two', 'three'] #}
You can also pass a limit argument:
If limit is positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string;
If limit is negative, all components except the last -limit are returned;
If limit is zero, then this is treated as 1.
{% set foo = "one,two,three,four,five"|split(',', 3) %}
{# foo contains ['one', 'two', 'three,four,five'] #}
If the delimiter is an empty string, then value will be split by equal chunks. Length is set by the limit argument (one character by default).
{% set foo = "123"|split('') %}
{# foo contains ['1', '2', '3'] #}
{% set bar = "aabbcc"|split('', 2) %}
{# bar contains ['aa', 'bb', 'cc'] #}
29striptags
The striptags filter strips SGML/XML tags and replaces adjacent whitespace characters by one space:
{{ some_html|striptags }}
You can also provide tags which should not be stripped:
{{ some_html|striptags('<br><p>') }}
In this example, the <br/>, <br>, <p>, and </p> tags won't be removed from the string.
30title
The title filter returns a titlecased version of the value. Words will start with uppercase letters, all remaining characters are lowercase:
{{ 'my first car'|title }}
{# outputs 'My First Car' #}
31trim
The trim filter strips whitespace (or other characters) from the beginning and end of a string:
{{ ' I like Twig. '|trim }}
{# outputs 'I like Twig.' #}
{{ ' I like Twig.'|trim('.') }}
{# outputs ' I like Twig' #}
{{ ' I like Twig. '|trim(side='left') }}
{# outputs 'I like Twig. ' #}
{{ ' I like Twig. '|trim(' ', 'right') }}
{# outputs ' I like Twig.' #}
32upper
The upper filter converts a value to uppercase:
{{ 'welcome'|upper }}
{# outputs 'WELCOME' #}
33url_encode
The url_encode filter percent encodes a given string as URL segment or an array as query string:
{{ "path-seg*ment"|url_encode }}
{# outputs "path-seg%2Ament" #}
{{ "string with spaces"|url_encode }}
{# outputs "string%20with%20spaces" #}
{{ {'param': 'value', 'foo': 'bar'}|url_encode }}
{# outputs "param=value&foo=bar" #}
34reverse
The reverse filter reverses a sequence, a mapping, or a string:
{% for user in users|reverse %}
...
{% endfor %}
{{ '1234'|reverse }}
{# outputs 4321 #}
35join
The join filter returns a string which is the concatenation of the items of a sequence:
{{ [1, 2, 3]|join }}
{# returns 123 #}
The separator between elements is an empty string per default, but you can define it with the optional first parameter:
{{ [1, 2, 3]|join('|') }}
{# outputs 1|2|3 #}
A second parameter can also be provided that will be the separator used between the last two items of the sequence:
{{ [1, 2, 3]|join(', ', ' and ') }}
{# outputs 1, 2 and 3 #}