3

I've got a generic newsletter template. Now some of our newsletters are in Spanish. It's overkill and more complicated for the admins to bother with settings up different locales, so instead I'd like to set the locale from the entry (currently using a dropdown).

All good, and I can use the |translate(language="") filter to achieve this using the value from the dropdown field.

Now the problem is that when formatting a date, it remains in English because it translated using the current locale, which is English.

I'm wondering whether I can manually override the locale in the template. {% set locale = 'es' %} or something.

Or if I can force the date to format using a specific locale.

Cheers.

  • Just to be clear, you're trying to avoid adding a new locale under Settings->Locales in the control panel? – Brad Bell Sep 1 '16 at 3:45
  • That's right. Newsletters are already linked to a category which is intrinsically linked to a language, so having to use locales properly would be confusing and doubling up on effort for the admin. – mijewe Sep 1 '16 at 8:41
3

Completely, 100% untested, but I think you'd be able to pull it off with a pretty simple plugin that added a new Twig filter (check the Twig Extensions switch).

From a template you'd something like:

{{ myDate|myDateFilter('es') }}

Then your plugin's myDateFilter method would do something like:

public function myDateFilter(\Twig_Environment $env, $date, $locale)
{
    $localeData = craft()->i18n->getLocaleData($locale);
    $dateFormatter = $localeData->getDateFormatter();

    return $dateFormatter->formatDateTime($date->getTimestamp());
}
| improve this answer | |
  • Brilliant - thanks so much. In the end I used the dateFormatter's format() function instead of formatDateTime(), but otherwise your untested code was bang on – mijewe Sep 2 '16 at 12:23

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.