Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is yii2's internationalization module case sensitive?

I have currently been dabbling with yii2's internationalization module but came across a curious behavior and was wandering.

Why does Yii::t('app','NEXT'), Yii::t('app','next') and Yii::t('app','Next') require separate translations?

I'm storing translation in a database. Is there any way I can make the translations case-insensitive? Or is there a specific reason why this is so?

like image 244
natral Avatar asked Jun 26 '17 17:06

natral


1 Answers

I believe it is an expected behaviour, as printing 'NEXT' and 'next' in some page looks surely different. So, for instance, if I want to see somewhere 'КЕЛЕСІ' instead of 'келесі', and I will receive only lower-case result, it would puzzle me in the first place.

Anyways it's better that the functionality is initialy case-sensitive, and you can make it case-insensitive (or make any string operators) for your needs.

Easy yet not recommended

The easiest way is to define a class with static function, where you'll lower any input and then consequently call the former Yii::t() function.

namespace app\components; // your namespace here

class Translator {
    public static function t($category, $message, $params = [], $language = null)
    {
        return \Yii::t($category, strtolower($message), $params, $language);
    }
}

And then instead of calling Yii::t('app', 'Next') you will use Translator::t('app', 'Next') and it'll fetch you the translation for the word 'next'


Second (more elegant) solution:

is to override main I18N component, that is configured in your web.php settings. First of all you should create a class and inherit it from yii\i18n\I18N component:

namespace app\components;

use yii\i18n\I18N;

class NewI18N extends I18N
{
    public function translate($category, $message, $params, $language)
    {
        return parent::translate($category, strtolower($message), $params, $language);
    }
}

..Next, open your web.php settings file and configure the 'i18n' component class as follow:

'components' => [
    'i18n' => [
        'class' => 'app\components\NewI18N', // Here it is
        'translations' => [
            'app*' => [
                'class' => 'yii\i18n\PhpMessageSource',
                'basePath' => '@app/messages',
            ],
        ],
    ],
...

That's all! In this second approach you don't have to use third-party Translator class, just call your familiar Yii::t() method and it'll lower strings automatically.

like image 57
Yerke Avatar answered Oct 07 '22 21:10

Yerke