You can use twig macros as if you're using normal PHP function in twig templates. Example below is used to creating dynamic links with query string parameters in twig template by using macro. For more information, read macro page.


We want to change the sort_by and sort_direction parameters of a a href tag when we click the relevant link.

{% macro sortColumn(label, field, direction) %}
{% if app.request.get('sort_direction') is defined %}
{% set direction = app.request.get('sort_direction') == 'asc' ? 'desc' : 'asc' %}
{% endif %}

<a href="{{ path(app.request.attributes.get('_route'),
app.request.query.all|merge({'sort_by': field, 'sort_direction': direction})) }}">{{ label }}</a>
{% endmacro %}
{% import _self as table %}


Sort By 'sender' link appears here: {{ table.sortColumn('Sender', 'sender', 'asc') }}
Sort By 'receiver' link appears here: {{ table.sortColumn('Receiver', 'receiver', 'asc') }}

Assume that our current link is app_test.php/emails?type=delivered. If we click "sender" or "receiver" links in our page, we get redirected to pages below.