Twig sort array of objects by field

Starting with Twig 2.12 (released on October 5, 2019) you can use the sort filter with an arrow function in the arrow argument. For example, to order by name: {% for user in users|sort((a, b) => a.name <=> b.name) %} <td>{{ user.name }}</td> <td>{{ user.lastname}}</td> <td>{{ user.age}}</td> {% endfor %} Twig docs: https://twig.symfony.com/doc/2.x/filters/sort.html

Does Twig have a null coalesce operator?

The null-coalescing operator was formally introduced in Twig 1.24 (Jan. 25, 2016). * adding support for the ?? operator Which means it’s now possible to do this… {{ title ?? “Default Title” }} You can even chain them together, to check multiple variables until a valid non-null value is found. {{ var1 ?? var2 ?? … Read more

A count in a loop

Apparently twig defines some loop variables inside the for-loop: {% for v in a %} {% if loop.index0 is even %} … {% endif %} {% endfor %}

How to remove duplicated items in array on Twig

Twig is a VIEW engine, and should not be used – in theory – to manipulate data. It’s a (very) good practice to use (assumingly) PHP to gather data, do all necessary manipulations and then pass the right data to your view. That said, here’s how you can do it in pure Twig syntax: {% … Read more

Using an environment variable (from `.env` file) in custom Twig function in Symfony 4

Here’s an easier way (Symfony 4) that does not involve any custom extensions. In my case, I wanted to set the Google Tag Manager Id as an environment variable in the .env file: GOOGLE_TAG_MANAGER_ID=”GTM-AAA12XX” Next, reference the environment variable in the config/packages/twig.yaml file: twig: globals: google_tag_manager_id: ‘%env(GOOGLE_TAG_MANAGER_ID)%’ Now you can use the tag manager value … Read more

Minus In twig block definition

Just read something about it in the documentation, not sure if this will also apply on {% block … %} tags. Twig whitespace control {% set value=”no spaces” %} {#- No leading/trailing whitespace -#} {%- if true -%} {{- value -}} {%- endif -%} {# output ‘no spaces’ #} There’s also another example given which … Read more

Calling a macro inside another macro in Twig

EDIT: As per cr4zydeejay’s answer Feb 7th 2021 the answer was updated to reflect the correct way in Twig 3.x Twig 3.x https://twig.symfony.com/doc/3.x/tags/macro.html When macro usages and definitions are in the same template, you don’t need to import the macros as they are automatically available under the special _self variable: <p>{{ _self.input(‘password’, ”, ‘password’) }}</p> … Read more