1

Usecase:

I'm sending out custom emails based on certain events to my users. These users have chosen a certain prefered locale in their profile settings and I'd like for those emails to be in that locale instead of in the locale of the control panel at the time of triggering the events.

So what I'm looking for is a way to set the relevant locale before rendering the email template with twig but I cant seem to find a way.


Relevant code

$mailer = craft()->email;
$mailToBeSent = new EmailModel();

craft()->templates->setTemplatesPath(CRAFT_TEMPLATES_PATH);
$mailToBeSent->toEmail = 'some.email@domain.com';

$mailToBeSent->subject = $subject;

$content = craft()->templates->render(
   '_emails/notification',
    [
        'userInfo' => $this->generateUserInfo($newUser),
    ]

);

$mailToBeSent->htmlBody = $content;
$mailer->sendEmail($mailToBeSent);

Let me know more information is needed or if something is unclear.

4

You can translate string in PHP and Twig via translate function

public static function t($message, $variables = array(), $source = null, $language = null, $category = 'craft')

Twig

{{ 'my string'|t() }}

PHP

Craft::t('my string');

So all you need to do is to wrap every string in your templates within the translate filter and pass the preferred local as an argument. For example

{{ 'my latest news'|t([], null, currentUser.locale) }}

If no parameter is set, Craft will use craft()->getLanguage() by default so you can do the following as well

$tmpLocale = craft()->getLanguage();
$user = craft()->userSession->getUser();
craft()->setLanguage($user->locale);
$content = craft()->templates->render(
   '_emails/notification',
   [
       'userInfo' => $this->generateUserInfo($newUser),
   ]
); 
$craft->setLanguage($tmpLocale);
1
  • damn not sure how, but I obviously overlooked the get/set language on the general craft object. Think I'll go with that approach as it's quite a bit of templates to modify otherwhise. Thanks!
    – mrsmn
    Aug 29 '18 at 14:02

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.