Drupal twig, different ways to translate.

After searching, once again, how to solve a translation in the Drupal 8 template system, it occurred to me that it would be good to always have a notes on hand with the different ways in which we can do a twig translation. Let us begin.

The best known and simple, we apply the filter | t to the text string:

    {{ 'Hello World!'|t }}

We can also use the | trans filter, but this is more useful when we use it as a block:

    {% trans %}Hello World!{% endtrans %}

It is clear that this form uses more code to do the same as the previous one, so block mode is usually used when we need to include html or variables along with the text string:

    {% trans %}Hello World! {{ date }}{% endtrans %}

And, mainly, we use it when we want to translate a text that can have a plural form:

    {% trans %}

         Hello World!

    {% plural count %}

        Hello {{ count }} Worlds!

    {% endtrans %}

And another variant that allows us |trans is to use contexts, with which we can translate the same text string in two different ways, in two different situations:

    {% trans with {'context': 'home', 'langcode': 'es'} %}

        Hello World!

    {% endtrans %}

    {% trans with {'context': 'node', 'langcode': 'es'} %}

        Hello World!

    {% endtrans %}

We can also save the translation provided by the filter | t in a variable:

    {% set my_text = 'Hello World!'|t %}

    {{ my_text }}

And this same formula could be used in block format if we want to add more than the text string:

    {% set my_text_html %}

        {{ 'Hello World!'|t }} <strong>{{date}}</strong>

    {% endset %}

    {{ my_text_html }}

As we saw in a previous post, this format can be useful when we add a twig link in which we want the text to have html.

Although if we only need to translate a text string for a link, we will put it directly on the link:

    {{ link('Hello World!'|t, 'internal:/', {'class':['hello-world__link']}) }}

I hope this summary is helpful for those who have to work daily with the translations in Twig.