1
votes

Does anyone know of a best practice in how to translate an e-mail send by SwiftMailer in Symfony? With or without twig.

I can come up with some options, but they all are incomplete.

First thing I can come up with is to create several twig files. Just like User.register.html.twig (default), User.register.nl_be.html.twig (dutch in belgium, based on your current url) and User.register.nl.html.twig (all dutch).

But there is a flaw with this approach, if my default template is edited, all other templates need to be altered too. Since we support a variety of languages, this is not maintainable.

Second I thought of using the translator of Symfony, by just using "labels" in one single template. For example:

<h1>{{ 'user.email.register.title'|trans }}</h1>
<div>{{ 'user.email.register.body'|trans }}</div>

The flaw in the first approach has been "fixed", but this contains another flaw. Now we need to manage the html in a translation file (yml, po, php, ini, etc.).

We can not just translate strings or placeholders, because e-mail templates are different based on the domain or language you are in. For example the header or footer are completely different. Sometimes marketing wants to add some other information to an e-mail only for a specific domain or language. And complete management around this, must be as simple as possible!

Does anyone have any idea on how to manage translatable e-mail, including changes in header/footer/etc. based on language/domain or other parameter?

1
Put already translated string in HTML: <?= translate('user.email.register.title'); ?>. Email will not parse your custom placeholder, so you need to send email with already translated textJustinas
@Justinas, I updated my question, because placeholders for only strings isn't an option. Sometimes fragments of an e-mail must be way different for specific languages or domains like the header or footer, or sometimes even some marketing information must be added.Leroy
Same thing. Use <?php if (): ?> to show/hide elementsJustinas
So you suggest to write around 50 if statements around a single element for all differentiating language or country visualizations including fallbacks? That's completely out of the question! Symfony has an amazing translation component, I want to use that to my advantage. Including the loose coupling of some html.Leroy
Just problem that your Email does not start any Symphony. It's plain HTML, no matter what framework you useJustinas

1 Answers

1
votes

You can DI the TranslatorInterface in your action

/**
* @param TranslatorInterface $translator
*/
public function switch(Request $request, TranslatorInterface $translator){
custom Stuff
}

Then you can check if the user is english, german or whatever.

    $lang = $user->getLang();

    if ($lang == 1) {
        $translator->setLocale('en');
    }

This will tranlate all your {{ 'mail.test'|trans }} Twig vars properly. This works really well and you will only have to maintain one html.twig file.