Yii offers some nice features to translate text to different languages using I18n.
Attribute labels are used heavily so it might be useful to define the translations in the model and use them by some kind of indexing instead of tranlating them.
I changed the attributeLabels() function in my model to translate labels like
‘abcfield’ => \Yii::t(‘app’, ‘Abcfield’),
which works like a charm.
I’m not sure if Yii stores the results somewhere in cache. If not, it might be a performance issue when all defined attributes are translated each time, regardless of how many of them are used in the view.
Or is it possible to pass an anonymous function which is executed only when needed?
I was also a bit confused at the beginning and got it mixed up with locale, but the language id is just the language part of locale. Locale contains language AND location (country). I was battling to set a locale as language id AND use the translations provided with yii at the same time, which uses just the language id.
That’s indeed a bit tricky. I understand and agree that for tranlations only the language part of the locale is required and should be used.
But Yii::$app->language and Yii::$app->sourceLanguage contains the locale, not just the language. To make it clear either the names should be changed or the type of content. What do you think?
Anyway - right now both returns (contains) the locale. Regarding to the documentation the default path to the translation files is the language id (that’s perfect). But yii uses the content of Yii::$app->language to detect the directory and not just the language part. Maybe this is a bug? If not the documentation should be enhanded to make it clear.
I did some additional tests and found the following:
default language is set to: public $language = ‘en_US’;
You can set the language to any string like: \Yii::$app->language = ‘fake language’;
yii::t looks for a directory name which equals to the content of $app->language
Adopting the default content and settig the language attribute to something like ‘fr-CA’ (French for Canada) then the directory must be called ‘fr-CA’.
Assume to want to support ‘fr-FR’ (French for France) as well, then you need to have a second directory named ‘fr-FR’.
This behavior is different to Yii version 1 where yii looked for a directory named ‘fr’.
I still believe that it should be clearly docuented what the Yii::$app->language should stand for (the language or locale).
It sholuld also made clear how this relates to the php class Locale which is used by the php intl extension to format dates and numbers.