Twig Filters

 Filters in Twig can be used to modify variables. Filters are separated from the variable by a pipe symbol. They may have optional arguments in parentheses. Multiple filters can be chained. The output of one filter is applied to the next.

Example:

{{ content|safe_join(", ")|lower }}

You may have to render an item before you filter it:

{{ item|render|filter }}

#Translation filters

This filter (alternatively, t) will run the variable through the Drupal t() function, which will return a translated string. This filter should be used for any interface strings manually placed in the template that will appear for users.

Example

<a href="{{ url('<front>') }}" title="{{ 'Home'|t }}" rel="home" class="site-logo"></a>

{% set name = '@label Introduction' |t({'@label': node.title.value}) %}

#placeholder

This filter escapes content to HTML and formats it using drupal_placeholder(), which makes it display as emphasized text.

Example

{% trans %}Submitted on {{ date|placeholder }}{% endtrans %}

#abs

The abs filter returns the absolute value.

Example 

{# number = -5 #}

{{ number|abs }}

{# outputs 5 #}

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

#date

The date filter formats a date to a given format:

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

to display the current date, filter the word "now"

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

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

List of Main twig filter are below

abs

batch

capitalize

column

convert_encoding

date

date_modify

first

keys

lower

split

title

trim

upper

No comments:

Write a program in PHP to reverse a number

A number can be written in reverse order. For example 12345 = 54321 <?php   $ num = 23456;   $ revnum = 0;   while ($ num > 1)   {   $...