11

I notice that Drupal 8 support {% trans %} which, according to the Symfony documentation (The i18n Extension), adds gettext support to Twig.

{{ |t }}, as far as I know, is the legacy way to add translatable strings into Drupal templates. According to the documentation, t() translates a string to the current language or a given language.

Both support multi-language website.

  • What are the differences between those extensions?
  • When should I use one over the other one?
  • I use trans for plurals. Otherwise simple t. For example "{% trans %} item {% plural count %} items {% endtrans %}" – user21641 Jan 17 '16 at 12:17
20

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

  • Awesome explanation. Thank you! The explanation on d.o was severely lacking (IMHO). Your more thorough explanation with examples helped me out a lot and gave me a couple of ideas. Especially the plural string example. That's pretty slick! – Tyler Youngblood Jun 7 '19 at 20:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.