6

So I've built a language switcher as per this answer.

I want the text for each link to be in the native language, for example I want the link to the English locale to say "Read this page in English" and the link to Spanish locale to say "Leer esta página en Español" etc.

However using the |t filter uses the locale that you're currently on, so if I'm on Spanish it says "Leer esta página en English".

Is there a way to pass in a parameter or something to say, for example, |t(Spanish).

Thanks!

9

Yes. You can see all of the arguments the |t filter supports by looking at the docs for Craft::t(), the function that |t maps to. Its $language argument defines the target language translation to use. So in your case you could do this:

{{ "Leer esta página en Español"|t(language="es") }}
  • Is there a way to use this as a fallback in case the current locale string is empty? I have a lot of incomplete translation locales and would like to fallback to the english version (100% translated) whenever a locale string is empty. Currently it's displaying the "key" value, which in my case is snake_cased – simonswiss Oct 16 '17 at 5:51
  • @simonswiss You could write a macro that sets the result of the |t filter to a variable, and then compares the variable with the original string. If equal, run it through |t once more, this time translating to English. Or you could just use the English strings as the keys, like Craft and Yii do, rather than some snake_cased version. – Brandon Kelly Oct 17 '17 at 10:53

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.