Filters

url_encode

{{ "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" #}

upper

{{ 'welcome'|upper }}

{# outputs 'WELCOME' #}

trim

{{ '  I like Twig.  '|trim }}

{# outputs 'I like Twig.' #}

{{ '  I like Twig.'|trim('.') }}

{# outputs '  I like Twig' #}

Arguments

  • character_mask: The characters to strip

title

{{ 'my first car'|title }}

{# outputs 'My First Car' #}

striptags

{{ some_html|striptags }}

split

{% 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'] #}
{% set foo = "123"|split('') %}
{# foo contains ['1', '2', '3'] #}

{% set bar = "aabbcc"|split('', 2) %}
{# bar contains ['aa', 'bb', 'cc'] #}

Arguments

  • delimiter: The delimiter
  • limit: The limit argument

sort

{% for user in users|sort %}
    ...
{% endfor %}

Slice

{% for i in [1, 2, 3, 4, 5]|slice(1, 2) %}
    {# will iterate over 2 and 3 #}
{% endfor %}

{{ '12345'|slice(1, 2) }}

{# outputs 23 #}
{% for i in [1, 2, 3, 4, 5]|slice(start, length) %}
    {# ... #}
{% endfor %}
{% for i in [1, 2, 3, 4, 5][start:length] %}
    {# ... #}
{% endfor %}

{{ '12345'[1:2] }} {# will display "23" #}

{# you can omit the first argument -- which is the same as 0 #}
{{ '12345'[:2] }} {# will display "12" #}

{# you can omit the last argument -- which will select everything till the end #}
{{ '12345'[2:] }} {# will display "345" #}

The slice filter works as the array_slice PHP function for arrays and mb_substr for strings with a fallback to substr.

If the start is non-negative, the sequence will start at that start in the variable. If start is negative, the sequence will start that far from the end of the variable.

If length is given and is positive, then the sequence will have up to that many elements in it. If the variable is shorter than the length, then only the available variable elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the variable. If it is omitted, then the sequence will have everything from offset up until the end of the variable.

Arguments

  • start: The start of the slice
  • length: The size of the slice
  • preserve_keys: Whether to preserve key or not (when the input is an array)

round

{{ 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.

Arguments

  • precision: The rounding precision
  • method: The rounding method

reverse

{% for user in users|reverse %}
    ...
{% endfor %}

{{ '1234'|reverse }}

{# outputs 4321 #}
{% for key, value in {1: "a", 2: "b", 3: "c"}|reverse %}
    {{ key }}: {{ value }}
{%- endfor %}

{# output: 0: c    1: b    2: a #}
{% for key, value in {1: "a", 2: "b", 3: "c"}|reverse(true) %}
    {{ key }}: {{ value }}
{%- endfor %}

{# output: 3: c    2: b    1: a #}

Arguments

  • preserve_keys: Preserve keys when reversing a mapping or a sequence.

replace

{{ "I like %this% and %that%."|replace({'%this%': foo, '%that%': "bar"}) }}

{# outputs I like foo and bar
   if the foo parameter equals to the foo string. #}

Arguments

  • replace_pairs: The placeholder values

raw

{% autoescape %}
    {{ var|raw }} {# var won't be escaped #}
{% endautoescape %}

number_format

{{ 200.35|number_format }}
{{ 9800.333|number_format(2, '.', ',') }}

If no formatting options are provided then Twig will use the default formatting options of:

  • 0 decimal places.
  • . as the decimal point.
  • , as the thousands separator.

Arguments

  • decimal: The number of decimal points to display
  • decimal_point: The character(s) to use for the decimal point
  • thousand_sep: The character(s) to use for the thousands separator

nl2br

{{ "I like shopping.\nYou will like it too."|nl2br }}
{# outputs

    I like shopping.<br />
    You will like it too.

#}

The nl2br filter pre-escapes the input before applying the transformation.

merge

{% 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.

{% 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.

lower

{{ 'WELCOME'|lower }}

{# outputs 'welcome' #}

length

{% if users|length > 10 %}
    ...
{% endif %}

last

{{ [1, 2, 3, 4]|last }}
{# outputs 4 #}

{{ { a: 1, b: 2, c: 3, d: 4 }|last }}
{# outputs 4 #}

{{ '1234'|last }}
{# outputs 4 #}

keys

{% for key in array|keys %}
    ...
{% endfor %}

json_encode

{{ data|json_encode() }}

Arguments

  • options: A bitmask of json_encode options ({{ data|json_encode(constant('JSON_PRETTY_PRINT')) }})

join

{{ [1, 2, 3]|join }}
{# returns 123 #}
{{ [1, 2, 3]|join('|') }}
{# outputs 1|2|3 #}

Arguments

  • glue: The separator

format

{{ "I like %s and %s."|format(foo, "bar") }}

{# outputs I like foo and bar
   if the foo parameter equals to the foo string. #}

first

{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}

{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}

{{ '1234'|first }}
{# outputs 1 #}

escape

The escape filter escapes a string for safe insertion into the final output. It supports different escaping strategies depending on the template context.

{{ product.title|escape }}
{{ product.title|e }}
{{ product.title|e }}
{# is equivalent to #}
{{ product.title|e('html') }}
{{ product.title|escape('js') }}
{{ product.title|e('js') }}

The escape filter supports the following escaping strategies:

  • html: escapes a string for the HTML body context.
  • js: escapes a string for the JavaScript context.
  • css: escapes a string for the CSS context. CSS escaping can be applied to any string being inserted into CSS and escapes everything except alphanumerics.
  • url: escapes a string for the URI or parameter contexts. This should not be used to escape an entire URI; only a subcomponent being inserted.
  • html_attr: escapes a string for the HTML attribute context.

Arguments

  • strategy: The escaping strategy
  • charset: The string charset

default

{{ var|default('var is not defined') }}

{{ var.foo|default('foo item on var is not defined') }}

{{ var['foo']|default('foo item on var is not defined') }}

{{ ''|default('passed var is empty')  }}
{{ var.method(foo|default('foo'))|default('foo') }}

Arguments

  • default: The default value

date_modify

{{ product.created_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 easily combine it with the date filter for formatting.

Arguments

  • modifier: The modifier

date

{{ product.created_at|date("m/d/Y") }}

The format specifier is the same as supported by date, except when the filtered data is of type DateInterval, when the format must conform to DateInterval::format instead.

The date filter accepts strings (it must be in a format supported by the strtotimefunction), DateTime instances, or DateInterval instances.

{{ "now"|date("m/d/Y") }}
{{ product.created_at|date("F jS \\a\\t g:ia") }}
{{ product.created_at is empty ? "" : product.created_at|date("m/d/Y") }}
{{ product.created_at|date("m/d/Y", "Europe/Paris") }}

Arguments

  • format: The date format
  • timezone: The date timezone

capitalize

{{ 'my first car'|capitalize }}

{# outputs 'My first car' #}

batch

New in version 1.12.3: The batch filter was added in Twig 1.12.3.

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}

<table>
{% for row in items|batch(3, 'No item') %}
    <tr>
        {% for column in row %}
            <td>{{ column }}</td>
        {% endfor %}
    </tr>
{% endfor %}
</table>
<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr>
        <td>d</td>
        <td>e</td>
        <td>f</td>
    </tr>
    <tr>
        <td>g</td>
        <td>No item</td>
        <td>No item</td>
    </tr>
</table>

Arguments

  • size: The size of the batch; fractional numbers will be rounded up
  • fill: Used to fill in missing items

abs

{# number = -5 #}

{{ number|abs }}

{# outputs 5 #}