0

I need to specify the language, which the drupal renderer uses, when generating a custom render array.

$renderArray = [
    "#theme" => "DNMBE_email",
    "#body" => [
        "#theme" => "DNMBE_emailBody_groupMessage",
        "#author" => $groupMessage->author,
        "#group" => $groupMessage->group,
        "#message" => $groupMessage->message,
    ],
    "#leadin" => $partials->leadin,
    "#leadout" => $partials->leadout,
];

$render = \Drupal
    ::service('renderer')
    ->renderRoot($renderArray);
$html = (string)$render;

#theme parameters resolve to twigs, which, among other things, contain {{ "From"|t }} markup which is incorrectly rendered as From.

I already posted a similar question, which was marked as duplicate, with the answer suggesting using \Drupal::languageManager()->setConfigOverrideLanguage($language). I do not get the expected result.

When using the t() function, you can supply as third parameter an array, which can be used to specify the language. The renderer however does not take extra parameters, thus also not passing it to twig.

I verified that /admin/config/regional/translate has got the translated string, case-sensitive. I also use ['#cache']['max-age'] = 0 and I don't "precalc"-store any Drupal objects.

  • Your first question was unspecific and the duplicate was handling content and config translation. When you are asking specifically about interface translation this was asked several times before. A good overall answer is drupal.stackexchange.com/a/270809/47547 and you find an example for the mentioned fake negotiator here drupal.stackexchange.com/a/216051/47547 – 4k4 May 27 at 7:13
  • Thank you, but that is somewhat a circular reference there. The first question clearly states that LanguageNegotiator does not help - I have the same usecase and I get the same results. There must be some missing part to this. – informatik-handwerk.de May 27 at 9:59
  • Normally a template using t() depends on the global language context. Although it has some upvotes I'm not advocating the fake negotiator to override the language and @Berdir doesn't seems to do it either in his answer. IMHO the straightforward way to make a template language specific is to put the language code in a template variable and use it as option for t(). – 4k4 May 27 at 11:25
1

Currently, the only working way seems to be by passing local context - including a langcode in the render array and using |t([], {'langcode': 'XX'}) resp. {% trans with {'langcode': 'XX'} %} as mentioned in https://www.drupal.org/project/drupal/issues/2049241

| improve this answer | |

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.