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') ->setFrom('[email protected]') ->setTo('[email protected]') ->setBody( $this->renderView( 'HelloBundle:Hello:email.txt.twig', array('name' => $name), 'nl_NL' // <-- This would be nice! ) ) ; $this->get('mailer')->send($message); return $this->render(...); }
You can pass the locale through as an argument when you use the trans filter (see diff: https://github.com/symfony/symfony/commit/3ea31a02630412b1c732ee1647a0724378f67665).
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:
# messages.fr.yml greeting: 'Bonjour'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With