Twig Filters

Square Online page templates support the following core Twig filters:

Square Online page templates support the Twig template language (version 3.x). For your convenience, excerpts of documentation for supported Twig filters are provided here under the BSD 3-Clause “New” or “Revised” License. Copyright © 2009-present by the Twig Team.

abs

The abs filter returns the absolute value.

{# number = -5 #}

{{ number|abs }}

{# outputs 5 #}

Back to top


batch

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:

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

<table>
    {% for row in items|batch(3, 'No item') %}
        <tr>
            {% for column in row %}
                <td>{{ column }}</td>
            {% endfor %}
        </tr>
    {% endfor %}
</table>

The above example will be rendered as:

<table>
    <tr>
        <td>a</td>
        <td>b</td>
        <td>c</td>
    </tr>
    <tr>
        <td>d</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
  • preserve_keys: Whether to preserve keys or not

Back to top


capitalize

The capitalize filter capitalizes a value. The first character will be uppercase, all others lowercase:

{{ 'my first car'|capitalize }}

{# outputs 'My first car' #}

Back to top


column

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'] #}

Arguments

  • name: The column name to extract

Back to top


convert_encoding

The convert_encoding filter converts a string from one encoding to another. The first argument is the expected output charset and the second one is the input charset:

{{ data|convert_encoding('UTF-8', 'iso-2022-jp') }}

Arguments

  • to: The output charset
  • from: The input charset

Back to top


country_name

The country_name filter returns the country name given its ISO-3166 two-letter code:

{# France #}
{{ 'FR'|country_name }}

By default, the filter uses the current locale. You can pass it explicitly:

{# États-Unis #}
{{ 'US'|country_name('fr') }}

Arguments

  • locale: The locale

Back to top


currency_name

The currency_name filter returns the currency name given its three-letter code:

{# Euro #}
{{ 'EUR'|currency_name }}

{# Japanese Yen #}
{{ 'JPY'|currency_name }}

By default, the filter uses the current locale. You can pass it explicitly:

{# yen japonais #}
{{ 'JPY'|currency_name('fr_FR') }}

Arguments

  • locale: The locale

Back to top


currency_symbol

The currency_symbol filter returns the currency symbol given its three-letter code:

{# € #}
{{ 'EUR'|currency_symbol }}

{# ¥ #}
{{ 'JPY'|currency_symbol }}

By default, the filter uses the current locale. You can pass it explicitly:

{# ¥ #}
{{ 'JPY'|currency_symbol('fr') }}

Arguments

  • locale: The locale

Back to top


date

The date filter formats a date to a given format:

{{ post.published_at|date("m/d/Y") }}

The date filter accepts strings. For instance, to display the current date, filter the word “now”:

{{ "now"|date("m/d/Y") }}

To escape words and characters in the date format use \\ in front of each character:

{{ post.published_at|date("F jS \\a\\t g:ia") }}

If the value passed to the date filter is null, it will return the current date by default. If an empty string is desired instead of the current date, use a ternary operator:

{{ post.published_at is empty ? "" : post.published_at|date("m/d/Y") }}

If no format is provided, the default one will be used: F j, Y H:i.

Timezone

By default, the date is displayed by applying the default timezone, but you can override it by explicitly specifying a timezone:

{{ post.published_at|date("m/d/Y", "Europe/Paris") }}

If the date is already a DateTime object, and if you want to keep its current timezone, pass false as the timezone value:

{{ post.published_at|date("m/d/Y", false) }}

Arguments

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

Back to top


date_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. You can combine it with the date filter for formatting.

Arguments

  • modifier: The modifier

Back to top


default

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') }}

{{ 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')  }}

Using the default filter on a boolean variable might trigger unexpected behavior, as false is treated as an empty value. Consider using ?? instead:

{% set foo = false %}
{{ foo|default(true) }} {# true #}
{{ foo ?? true }} {# false #}

Arguments

  • default: The default value

Back to top


escape

The escape filter escapes a string using strategies that depend on the context.

By default, it uses the HTML escaping strategy:

<p>
    {{ example|escape }}
</p>

For convenience, the e filter is defined as an alias:

<p>
    {{ example|e }}
</p>

The escape filter can also be used in other contexts than HTML thanks to an optional argument which defines the escaping strategy to use:

{{ example|e }}
{# is equivalent to #}
{{ example|e('html') }}

And here is how to escape variables included in JavaScript code:

{{ example|escape('js') }}
{{ example|e('js') }}

The escape filter supports the following escaping strategies for HTML documents:

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

When using automatic escaping, Twig tries to not double-escape a variable when the automatic escaping strategy is the same as the one applied by the escape filter; but that does not work when using a variable as the escaping strategy:

{% set strategy = 'html' %}

{% autoescape 'html' %}
    {{ var|escape('html') }}   {# won't be double-escaped #}
    {{ var|escape(strategy) }} {# will be double-escaped #}
{% endautoescape %}

Arguments

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

Back to top


filter

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

It also works with mappings:

{% set sizes = {
    xs: 34,
    s:  36,
    m:  38,
    l:  40,
    xl: 42,
} %}

{% for k, v in sizes|filter(v => v > 38) -%}
    {{ k }} = {{ v }}
{% endfor %}
{# output l = 40 xl = 42 #}

The arrow function also receives the key as a second argument:

{% for k, v in sizes|filter((v, k) => v > 38 and k != "xl") -%}
    {{ k }} = {{ v }}
{% endfor %}
{# output l = 40 #}

Note that the arrow function has access to the current context.

Arguments

  • array: The sequence or mapping
  • arrow: The arrow function

Back to top


first

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

Back to top


format

The format filter formats a given string by replacing the placeholders:

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

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

See also replace.

Back to top


format_currency

The format_currency filter formats a number as a currency:

{# €1,000,000.00 #}
{{ '1000000'|format_currency('EUR') }}

You can pass attributes to tweak the output:

{# €12.34 #}
{{ '12.345'|format_currency('EUR', {rounding_mode: 'floor'}) }}

{# €1,000,000.0000 #}
{{ '1000000'|format_currency('EUR', {fraction_digit: 4}) }}

The list of supported options:

  • grouping_used;
  • decimal_always_shown;
  • max_integer_digit;
  • min_integer_digit;
  • integer_digit;
  • max_fraction_digit;
  • min_fraction_digit;
  • fraction_digit;
  • multiplier;
  • grouping_size;
  • rounding_mode;
  • rounding_increment;
  • format_width;
  • padding_position;
  • secondary_grouping_size;
  • significant_digits_used;
  • min_significant_digits_used;
  • max_significant_digits_used;
  • lenient_parse.

By default, the filter uses the current locale. You can pass it explicitly:

{# 1.000.000,00 € #}
{{ '1000000'|format_currency('EUR', locale='de') }}

Arguments

  • currency: The currency
  • attrs: A map of attributes
  • locale: The locale

Back to top


format_date

The format_date filter formats a date. It behaves in the exact same way as the format_datetime filter, but without the time.

Arguments

  • locale: The locale
  • dateFormat: The date format
  • pattern: A date time pattern
  • timezone: The date timezone
  • calendar: The calendar (“gregorian” by default)

Back to top


format_datetime

The format_datetime filter formats a date time:

{# Aug 7, 2019, 11:39:12 PM #}
{{ '2019-08-07 23:39:12'|format_datetime() }}

Format

You can tweak the output for the date part and the time part:

{# 23:39 #}
{{ '2019-08-07 23:39:12'|format_datetime('none', 'short', locale='fr') }}

{# 07/08/2019 #}
{{ '2019-08-07 23:39:12'|format_datetime('short', 'none', locale='fr') }}

{# mercredi 7 août 2019 23:39:12 UTC #}
{{ '2019-08-07 23:39:12'|format_datetime('full', 'full', locale='fr') }}

Supported values are: none, short, medium, long, and full.

{# 11 oclock PM, GMT #}
{{ '2019-08-07 23:39:12'|format_datetime(pattern="hh 'oclock' a, zzzz") }}

Locale

By default, the filter uses the current locale. You can pass it explicitly:

{# 7 août 2019 23:39:12 #}
{{ '2019-08-07 23:39:12'|format_datetime(locale='fr') }}

Timezone

By default, the date is displayed by applying the default timezone, but you can override it by explicitly specifying a timezone:

{{ datetime|format_datetime(locale='en', timezone='Pacific/Midway') }}

If the date is already a DateTime object, and if you want to keep its current timezone, pass false as the timezone value:

{{ datetime|format_datetime(locale='en', timezone=false) }}

Arguments

  • locale: The locale
  • dateFormat: The date format
  • timeFormat: The time format
  • pattern: A date time pattern
  • timezone: The date timezone name
  • calendar: The calendar (“gregorian” by default)

Back to top


format_number

The format_number filter formats a number:

{{ '12.345'|format_number }}

You can pass attributes to tweak the output:

{# 12.34 #}
{{ '12.345'|format_number({rounding_mode: 'floor'}) }}

{# 1000000.0000 #}
{{ '1000000'|format_number({fraction_digit: 4}) }}

The list of supported options:

  • grouping_used;
  • decimal_always_shown;
  • max_integer_digit;
  • min_integer_digit;
  • integer_digit;
  • max_fraction_digit;
  • min_fraction_digit;
  • fraction_digit;
  • multiplier;
  • grouping_size;
  • rounding_mode;
  • rounding_increment;
  • format_width;
  • padding_position;
  • secondary_grouping_size;
  • significant_digits_used;
  • min_significant_digits_used;
  • max_significant_digits_used;
  • lenient_parse.

Besides plain numbers, the filter can also format numbers in various styles:

{# 1,234% #}
{{ '12.345'|format_number(style='percent') }}

{# twelve point three four five #}
{{ '12.345'|format_number(style='spellout') }}

{# 12 sec. #}
{{ '12'|format_duration_number }}

The list of supported styles:

  • decimal;
  • currency;
  • percent;
  • scientific;
  • spellout;
  • ordinal;
  • duration.

As a shortcut, you can use the format_*_number filters by replacing * with a style:

{# 1,234% #}
{{ '12.345'|format_percent_number }}

{# twelve point three four five #}
{{ '12.345'|format_spellout_number }}

You can pass attributes to tweak the output:

{# 12.3% #}
{{ '0.12345'|format_percent_number({rounding_mode: 'floor', fraction_digit: 1}) }}

By default, the filter uses the current locale. You can pass it explicitly:

{# 12,345 #}
{{ '12.345'|format_number(locale='fr') }}

Arguments

  • locale: The locale
  • attrs: A map of attributes
  • style: The style of the number output

Back to top


format_time

The format_time filter formats a time. It behaves in the exact same way as the format_datetime filter, but without the date.

Arguments

  • locale: The locale
  • timeFormat: The time format
  • pattern: A date time pattern
  • timezone: The date timezone
  • calendar: The calendar (“gregorian” by default)

Back to top


join

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

Arguments

  • glue: The separator
  • and: The separator for the last pair of input items

Back to top


json_encode

The json_encode filter returns the JSON representation of a value:

{{ data|json_encode() }}

Arguments

  • options: A bitmask of json_encode options: {{ data|json_encode(constant('JSON_PRETTY_PRINT')) }}. Combine constants using bitwise operators: {{ data|json_encode(constant('JSON_PRETTY_PRINT') b-or constant('JSON_HEX_QUOT')) }}

Back to top


json_decode

The json_decode filter returns an array or object that is parsed from a JSON string:

{{ data|json_decode() }}

Arguments

  • associative: When true, JSON objects will be returned as associative arrays; when false, JSON objects will be returned as objects
  • depth: Maximum nesting depth of the structure being decoded
  • options: A bitmask of json_decode

Back to top


keys

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 %}

Back to top


language_name

The language_name filter returns the language name given its two-letter code:

{# German #}
{{ 'de'|language_name }}

By default, the filter uses the current locale. You can pass it explicitly:

{# allemand #}
{{ 'de'|language_name('fr') }}

{# français canadien #}
{{ 'fr_CA'|language_name('fr_FR') }}

Arguments

  • locale: The locale

Back to top


last

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

Back to top


length

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 %}

Back to top


locale_name

The locale_name filter returns the locale name given its two-letter code:

{# German #}
{{ 'de'|locale_name }}

By default, the filter uses the current locale. You can pass it explicitly:

{# allemand #}
{{ 'de'|locale_name('fr') }}

{# français (Canada) #}
{{ 'fr_CA'|locale_name('fr_FR') }}

Arguments

  • locale: The locale

Back to top


lower

The lower filter converts a value to lowercase:

{{ 'WELCOME'|lower }}

{# outputs 'welcome' #}

Back to top


map

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.

Arguments

  • arrow: The arrow function

Back to top


merge

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.

If you want to ensure that some values are defined in an array (by given default values), reverse the two elements in the call:

{% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}

{% set items = { 'apple': 'unknown' }|merge(items) %}

{# items now contains { 'apple': 'fruit', 'orange': 'fruit' } #}

Back to top


nl2br

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.

#}

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

Back to top


number_format

The number_format filter formats numbers.

{{ 200.35|number_format }}

You can control the number of decimal places, decimal point, and thousands separator using the additional arguments:

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

To format negative numbers or math calculation, wrap the previous statement with parentheses (needed because the precedence of operators):

{{ -9800.333|number_format(2, '.', ',') }} {# outputs : -9 #}
{{ (-9800.333)|number_format(2, '.', ',') }} {# outputs : -9,800.33 #}
{{  1 + 0.2|number_format(2) }} {# outputs : 1.2 #}
{{ (1 + 0.2)|number_format(2) }} {# outputs : 1.20 #}

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.

These defaults can be changed through the core extension:

$twig = new \Twig\Environment($loader);
$twig->getExtension(\Twig\Extension\CoreExtension::class)->setNumberFormat(3, '.', ',');

The defaults set for number_format can be over-ridden upon each call using the additional parameters.

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

Back to top


reduce

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

The reduce filter takes an initial value as a second argument:

{{ numbers|reduce((carry, v, k) => carry + v * k, 10) }}
{# output 18 #}

Note that the arrow function has access to the current context.

Arguments

  • arrow: The arrow function
  • initial: The initial value

Back to top


replace

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

Arguments

  • from: The placeholder values as a hash

See also format.

Back to top


reverse

The reverse filter reverses a sequence, mapping, or string:

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

{{ '1234'|reverse }}

{# outputs 4321 #}

For sequences and mappings, numeric keys are not preserved. To reverse them as well, pass true as an argument to the reverse filter:

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

Back to top


round

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.

The // operator is equivalent to |round(0, 'floor').

Arguments

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

Back to top


slice

The slice filter extracts a slice of a sequence, mapping, or 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 #}

You can use any valid expression for both the start and the length:

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

As syntactic sugar, you can also use the [] notation:

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

{# you can use a negative value -- for example to remove characters at the end #}
{{ '12345'[:-2] }} {# will display "123" #}

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)

Back to top


slug

The slug filter transforms a given string into another string that only includes safe ASCII characters.

Here is an example:

{{ 'Wôrķšƥáçè ~~sèťtïñğš~~'|slug }}
Workspace-settings

The default separator between words is a dash (-), but you can define a selector of your choice by passing it as an argument:

{{ 'Wôrķšƥáçè ~~sèťtïñğš~~'|slug('/') }}
Workspace/settings

The slugger automatically detects the language of the original string, but you can also specify it explicitly using the second argument:

{{ '...'|slug('-', 'ko') }}

Arguments

  • separator: The separator that is used to join words (defaults to -)
  • locale: The locale of the original string (if none is specified, it will be automatically detected)

Back to top


sort

The sort filter sorts an array:

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

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

Arguments

  • arrow: An arrow function

Back to top


spaceless

The spaceless filter removes whitespace between HTML tags. Note that neither whitespace within HTML tags nor whitespace in plain text is affected:

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

As the filter uses a regular expression behind the scenes, its performance is directly related to the text size you are working on (remember that filters are executed at runtime).

Back to top


split

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'] #}

Arguments

  • delimiter: The delimiter
  • limit: The limit argument

Back to top


striptags

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.

Arguments

  • allowable_tags: Tags which should not be stripped

Back to top


timezone_name

The timezone_name filter returns the timezone name given a timezone identifier:

{# Central European Time (Paris) #}
{{ 'Europe/Paris'|timezone_name }}

{# Pacific Time (Los Angeles) #}
{{ 'America/Los_Angeles'|timezone_name }}

By default, the filter uses the current locale. You can pass it explicitly:

{# heure du Pacifique nord-américain (Los Angeles) #}
{{ 'America/Los_Angeles'|timezone_name('fr') }}

Arguments

  • locale: The locale

Back to top


title

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' #}

Back to top


trim

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.' #}

Arguments

  • character_mask: The characters to strip
  • side: The default is to strip from the left and the right (both) sides, but left and right will strip from either the left side or right side only

Back to top


upper

The upper filter converts a value to uppercase:

{{ 'welcome'|upper }}

{# outputs 'WELCOME' #}

Back to top


url_encode

The url_encode filter 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" #}