robert
robert

Reputation: 1

yii2 i18n internationalization?

what do you think

step 1 web.php

'language' => 'de',
'components' => [
    'i18n' => [
        'translations' => [
            'app*' => [
                'class' => 'yii\i18n\PhpMessageSource',
                'basePath' => '@app/messages',
                'sourceLanguage' => 'en',
                'fileMap' => [
                    'app' => 'app.php',
                    'app/error' => 'error.php',`
                    .....

Step2 I created the -foldert messages, and I added three folder in messages folder (en, fr, de) and created three file(each contained one)-app.php

'language' => 'de', when i change 'language' => 'hu' Works with translation

step 3 But because I am a beginner I do not know what's next. I created two buttons but I can not write the Controller.

view/index.php

<a href="<?php echo Url::to(['']); ?>">German</a><br>
<a href="<?php echo Url::to(['']); ?>">Hungarian</a>

My question is how could the button to switch the language,Need to create a Controller, or work without it, it's how?

step 4 ?

Thanks

Upvotes: 0

Views: 761

Answers (2)

Abdul Mueid
Abdul Mueid

Reputation: 31

Create an action to Set Language in your controller for example SiteController i.e.

public function actionSetLang($lang)
{
    switch ($lang) {
        case "en":
            \Yii::$app->language = "en";
            break;
        case "de":
            \Yii::$app->language = "de";
            break;
        case "hu":
            \Yii::$app->language = "hu";
            break;
        default:
            \Yii::$app->language = "en";
    }
    $this->goBack();
}

Then in your view you can set up your buttons i.e.

<a href="<?php echo Url::to(['site/setLang', 'lang' => 'hu']); ?>">Hungarian</a>
<a href="<?php echo Url::to(['site/setLang', 'lang' => 'de']); ?>">German</a>

The above is a very simple approach. Ideally you want to use cookies to store the user's preferred language in the browser, so the users don't have to change the language every time they visit the page. The cookies can be implemented within the setLang action. I will skip the cookies implementation as they are out of the scope of this question.

Upvotes: 1

Rickert
Rickert

Reputation: 1675

You could use this to set your language:

Yii::$app->language = 'ru_RU';

use this function in your controller:

    public function init()
    {
      //set here your language
      parent::init();

    }

And it wil works for all the functions of that controller.

EDIT:

The first function sets the languages for the rest of the application. when you call that function the rest of the Yii::t() labels will be in that language if the label exsists in that language. de init is a function that is always called before the action in a controller every controller have that function. so if you set a language there the rest of the function will be in that language

Upvotes: 0

Related Questions