Pavel Šliachtovič
Pavel Šliachtovič

Reputation: 41

Silverstripe 3.3: how to translate date month variable in a template?

On my page I have a date variable. I wish to translate it's shortened month name by locale (in my case Lithuanian).

I've set up the translations in langed/lang/lt_LT.yml:

Month:
    Jan: 'Sau'
    Feb: 'Vas'
    Mar: 'Kov'
    Apr: 'Bal'
    ...

And in my template when I put

$Date.Format(M d)

It gives the month and day always in English, no matter the locale (ex. "Apr 18", I need "Bal 18" in this case).

I have attempted to try to put the variable of Month into translation quotes of .ss template:

<%t Month.$Date.Format('M') %>

But it doesn't work. It throws an error:

"[User Error] Uncaught SSTemplateParseException: Parse error in template on line 16. Error was: Malformed opening block tag t. Perhaps you have tried to use operators?"

Can anyone please explain to me how am I doing this wrong?

Upvotes: 4

Views: 878

Answers (2)

Rudiger
Rudiger

Reputation: 6769

The way I've implemented this is put a function on the controller:

public function MonthForVar($var) {
    return _t("Month.$var");
}

and then you can call $MonthForVar($Date) in your template. Don't forget if you're doing it in a loop to go $Up.MonthForVar($Date)

** Should add that wmk's answer is better for date format however I was lead here from Google when I'm trying to translate something non-date related, in which case this should work.

Upvotes: 1

wmk
wmk

Reputation: 4626

You can use $Date.FormatI18N('%b') which utilizes strftime() which in turn needs your locale installed on the server to translate it. If not you just get the english (or default) locale.

See this gist for an extension to get the current locale in your controller.

Upvotes: 4

Related Questions