Both the {{ |t }}
filter and {% trans %} ... {% endtrans %}
blocks, when used in the context of Twig template file in Drupal, are part of the Drupal localization system. And translation for strings processed with either one are handled in the same way, and via localize.drupal.org. For simple strings of text they can be used interchangeably, however the %trans
block has some additional useful features for complex strings.
The difference is that the t
filter only allows for simple strings, while using a %trans
block allows the use of dynamic placeholders in the string. Much like using the php t()
function.
Here's a few examples:
Simple string translation via t
filter:
{{ 'Hello Stack Exchange!'|t }}
String translation with placeholder:
{% trans %}Hello {{ user.name }}, today's date is {{ date|placeholder }}.{% endtrans %}
Placeholders are escaped by default, but can also be left-unescaped {{ var|passthrough }}
or formatted as a placeholder {{ var|placeholder }}
. This is equivalent to using @string, !string, and %string in the t() function respectively.
You can also use %trans
blocks in order to format plural strings.
{% trans %}
There is 1 comment.
{% plural count %}
There are {{ count }} comments.
{% endtrans %}
For simple strings there are really no rules about when you should use |t
vs. %trans
. So I would recommend using whatever is easiest to read in your template. In my experience using the |t
filter works well for short strings, while the %trans
block is easier for longer strings of text.
More information about usage can be found here: https://www.drupal.org/node/2357633 and here https://www.drupal.org/developing/api/8/localization