2

In Drupal 8, with English and German enabled, I am trying to translate a variable using a specific context.

When visiting a page in German:

{% trans with {'context': 'Long month name'} %}
    March
{% endtrans %}

This outputs März which is fine.


{% set month = 'March' %}

{% trans with {'context': 'Long month name'} %}
   {{ month }}
{% endtrans %}

This outputs March which is not fine.


Why? And how am I supposed to translate variables in a Twig template?

Here is the documentation I have read.


Edit: https://www.drupal.org/node/2357633

This mentions:

The t filter will run the variable through the Drupal t() function, which will return a translated string. This filter should be used for any interface strings manually placed in the template that will appear for users.

And also:

The following patterns are unsafe and should not be used because they pass a variable directly to translation. This not only inflates the list of strings for translation but is also a potential vulnerability, particularly if the output can be entered by a user.

{{ var1|t }}
{{ var1|placeholder }}
{% trans %}{{ var1 }}{% endtrans %}

2 Answers 2

2

A variable is like a placeholder. It does not get translated. Context or not is not relevant. Your example basically translates to t('@month', ['@month' => 'March'], ['context' => 'Long month name']). It simply doesn't work like that.

if you need to translate march and then put it as a variable in a bigger text, you first need to translate March on its own using the context and then put it in the other text.

I'm not sure if you can do that within twig, but I suppose that's only a simplified example and you actually get month injected? Then you need to translate the month name at the source, where it is provided to the template. If that is not the case, then you need to explain your actual use case, because I suppose this is not it..

1
  • That all makes sense, thank you. Will edit my question in a minute with a bit of information I just found.
    – MrUpsidown
    Commented Jun 2, 2016 at 10:56
10

In Drupal 8, you can translate a string in a Twig file with a specified context in two ways :

{{ "Text to translate"|t({}, {'context' : 'Context name'}) }}

and

{% trans with {'context': 'Context name'} %}
    Text to translate
{% endtrans %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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