rolandow rolandow - 3 years ago 578
Twig Question

Forcing the Twig Locale

I would like to use the Twig template system to template my e-mails. The locale of the e-mail should be based on a user setting, not from the session or request locale. How can I force the locale when rendering a Twig template?

The manual does mention how to force the locale for the Translator. But i'd like pass this locale to the render() method, in order to have the translations inside the twig template to be rendered in this locale.

This is different from using into in the template, because I think this forces a translation inside the template in a specific locale.

So, taking the example from Symfony, I'm looking for something like this:

public function indexAction($name)
$message = \Swift_Message::newInstance()
->setSubject('Hello Email')
array('name' => $name),
'nl_NL' // <-- This would be nice!

return $this->render(...);

Answer Source

You can pass the locale through as an argument when you use the trans filter (see diff:

So you could pass another user_locale variable in your render method in your controller (or pass through the whole user object instead of passing name and user_locale separately, or use app.user in your template if the user will be logged in, etc... (depending on your application obviously)), then in your email template you can have something like this:

{{ 'greeting' | trans({}, "messages", user_locale) }} {{ name | title }}
{# rest of email template with more translation strings #}

Then in your translation file for that locale (assuming you're using yaml) just have something like this and the translations will work nicely for you on the fly:

greeting: 'Bonjour'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download