The URL pattern to support the multilanguage view

There are different ways to display the same view in different languages. A basic approach to support multilanguage views could be to insert a language code at the start of the route. For example, the previous route news/index will become en/news/index in English language, it/news/index in Italian language, fr/news/index in French language, and so on.

Append this rule in the rules property of UrlManager:

[
    'pattern' => '<lang:w+>/<controller>/<action>',
    'route' => '<controller>/<action>',
],

All the requests that have a language ID as the prefix in the path info, will be matched and passed to the <controller>/<action> route with the $lang parameters passed in GET.

Now, create a new action named actionInternationalIndex in NewsController to test the multilanguage support:

public function actionInternationalIndex()
{
    // if missing, value will be 'en'
    $lang = Yii::$app->request->get('lang', 'en');
    
    Yii::$app->language = $lang;

    return $this->render('internationalIndex');
}

In this action, $lang is taken from GET parameters. If the request does not contain the $lang parameter, the en value will be used as default.

Create new view in views/news/internationalIndex.php to check the language code passed to the URL.

Requested language for this page is:
<br />
<b><?php echo Yii::$app->language ?></b>

Verify whether this action is working correctly by visiting http://hostname/news/international-index:

The URL pattern to support the multilanguage view

Setting the English language

We are visualizing this page in English because no language code was passed to the URL. Consequently, the default language code, en, has been used. However, if we write the language code in the URL, the result will change.

For example, pointing to http://hostname/basic/web/it/news/international-index will display the following:

The URL pattern to support the multilanguage view

Setting the Italian language

This response gives us the confirmation that we have used it as the language code.

Note

In this simple approach to support multi language, we get the $lang value from the request, as we have done in actionInternationalIndex; however, this is redundant and has to be generalized in all the requests. We could create a BaseController class as the base class for every Controller and then override the beforeAction() method, where we can set the Yii::$app->language parameter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.171.202