Home> php教程> PHP开发> body text

Yii2 framework study notes (3) -- Language and internationalization

黄舟
Release: 2016-12-30 09:44:13
Original
1807 people have browsed it

The internationalization function is generally rarely used, but for learning, it is still necessary to get in touch with it.

The most commonly used method for internationalization is \Yii::t. The official document is as follows

t() public static method Translates a message to the specified language. This is a shortcut method of yii\i18n\I18N::translate(). The translation will be conducted according to the message category and the target language will be used. You can add parameters to a translation message that will be substituted with the corresponding value after translation. The format for this is to use curly brackets around the parameter name as you can see in the following example:
Copy after login
[code]$username = 'Alexander'; echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);
Copy after login
Further formatting of message parameters is supported using the PHPintl extensions message formatter. See yii\i18n\I18N::translate() formore details. public static stringt ($category, $message, $params = [],$language = null ) $category string The message category. $message string The message to be translated. $params array The parameters that will be used to replace the corresponding placeholders in the message. $language string The language code (e.g.en-US,en).If this is null, the current application language will be used. return string The translated message.
Copy after login

There are 4 parameters, but the first two are commonly used.

The first one is the group, and the definition of the group is placed under config/main-local.php.

Yii2 uses English (en-US) by default, and now adds Chinese support (zh-CN)

Add the following block under component

'components' => [ ... 'i18n' => [ 'translations' => [ 'common' => [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => '@common/messages', 'fileMap' => [ 'common' => 'common.php', ], ], ], ], ... ],
Copy after login

This code definition A group named common is created. The default class yii\i18n\PhpMessageSource is used to parse the translation file. The translation file is placed under common/messages and the translation file is common.php.

According to the configuration, establish the following directory structure

Yii2 framework study notes (3) -- Language and internationalization

The translation files are organized in an array, and the content is as follows

 '注册', 'Login' => '登陆', 'Logout' => '登出', 'Home' => '首页', 'Contact' => '反馈', 'About' => '关于', ];
Copy after login

Then we Do the translation in the layouts file and modify it in /views/layouts/main.php as follows:

$menuItems = [ //['label' => 'Home', 'url' => ['/site/index']], //['label' => 'About', 'url' => ['/site/about']], //['label' => 'Contact', 'url' => ['/site/contact']], ['label' => \Yii::t('common', 'Home'), 'url' => ['/site/index']], ['label' => \Yii::t('common', 'About'), 'url' => ['/site/about']], ['label' => \Yii::t('common', 'Contact'), 'url' => ['/site/contact']], ];
Copy after login

Open the page and see if it takes effect.

Unfortunately, it does not take effect. . . . .

Yii2 framework study notes (3) -- Language and internationalization

The reason is that the root language of the website is still en-US and needs to be configured as zh-CN.

In common/config/main-local.php, add the following configuration:

 'zh-CN', ... ];
Copy after login

Check again whether it takes effect.

Yii2 framework study notes (3) -- Language and internationalization

You can see that the translation has taken effect.

But the main reason for using the Yii::t method is to achieve multi-language. If you only display one language, it is better to do hardcode (the yii2 framework actually does the hardcode language display)

yii2 does not provide a ready-made control for switching languages, so we need to develop one ourselves.

The implementation refers to http://www.yiiframework.com/wiki/294/seo-conform-multilingual-urls-language-selector-widget-i18n/, and has been moderately simplified without doing SEO aspects. consideration.

The main idea of implementation is to save the language selected by the user in a cookie, and set the language to the value in the cookie before each user visits the page. Why do you need to set the language each time? The reasons are as follows

Note: If we don't set Yii::app()->language explicitly for each request, it will be equal to its default value set in the confg file. If it is not set in the config file, it will be equal to the value Yii::app()->sourceLanguage, which defaults to 'en_us'.

The general meaning is that if not every time If the value is set, the system will use the default language, which is usually English.

1. Prepare materials, both sides of the flag, put them under frontend/web/image/ and name them en.png and zh.png.

Yii2 framework study notes (3) -- Language and internationalization

2. Configure the available languages in /common/config/main-local.php for us to call in the control

 'zh-CN', 'components' => [ ... ], 'params' => [ 'availableLanguages' => [ 'zh-CN' => ['img' => 'image/zh.png', 'desc' => '中文'], 'en-US' => ['img' => 'image/en.png', 'desc' => 'English'], ], ], ... ];
Copy after login

3. In Create a new php file under /common/widgets/ and name it LanguageSelector.php. The content is as follows:

language; $avLang = Yii::$app->params['availableLanguages']; $isMatch = false; foreach ($avLang as $key => $value) { if($key == $lang) { $tag = LanguageSelector::buildImgTag($value['img'], $value['desc']); $isMatch = true; } } if(!$isMatch) { $tag = LanguageSelector::buildImgTag($avLang[0]['img'], $avLang[0]['desc']); } $return = [ 'label' => $tag, 'items' => LanguageSelector::buildMenuItems($avLang), ]; return $return; } private static function buildImgTag($src, $desc) { return '' . $desc . ''; } private static function buildMenuItems($langs) { foreach ($langs as $key => $value) { $link = Html::a(LanguageSelector::buildImgTag($value['img'], $value['desc']) . ' ' . $value['desc'], Url::home(), [ 'title' => LanguageSelector::buildImgTag($value['img'], $value['desc']) . ' ' . $value['desc'], 'onclick'=>" $.ajax({ type :'POST', cache : false, url : '" . Url::toRoute("ajax/lang") . "', data: { _lang : '" . $key . "' }, success : function(response) { window.location.reload(); } });return false;", ]); $menuItems[] = '
  • ' . $link . '
  • '; } return $menuItems; } }
    Copy after login

    The main thing to do is:

    Read the configuration items in main-local.php , forming an array.
    Rendering menu.
    Bind events to the buttons in the menu. When clicked, an ajax request is triggered. After ajax returns successfully, the page is refreshed.

    4. Add a controller that handles ajax. Create a new AjaxController.php under frontend/controllers and add the following code:

    language = $lang; $cookie = new cookie([ 'name' => '_lang', 'value' => $lang, ] ); $cookie->expire = time() + (60*60*24*365); // (1 year) Yii::$app->response->cookies->add($cookie); } return "success"; } }
    Copy after login

    The important thing is to set $layouts to false to prevent ajax from returning to render unnecessary things.

    5. Add an action (Behaviors) to modify the language every time the user visits the page.
    Under common/components (if there is no such directory, create a new directory), create a new SelectLanguageBehavior.php with the following content

     'beforeRequest', ]; } public function beforeRequest($event) { $app = Yii::$app; $lang = SelectLanguageBehavior::getSelectedLanguage(Yii::$app->request->cookies->getValue('_lang')); $app->language = $lang; } public static function getSelectedLanguage($val) { $langs = Yii::$app->params['availableLanguages']; foreach ($langs as $key=>$value) { if($val == $key) { return $val; } } return key($langs); } }
    Copy after login

    6. Bind the action to the system.
    Add the as beginRequest item in common/config/main-local.php

     'zh-CN', 'components' => [ ... ], ... 'as beginRequest' => [ 'class' => 'common\components\SelectLanguageBehavior', ], ];
    Copy after login

    7. Add the control to the page.
    In frontend/views/layouts/main.php, add code to display our control. Because the control contains html code, we must prevent it from escaping

    ... if (Yii::$app->user->isGuest) { $menuItems[] = ['label' => Yii::t('common', 'Signup'), 'url' => ['/site/signup']]; $menuItems[] = ['label' => Yii::t('common', 'Login'), 'url' => ['/site/login']]; } else { $menuItems[] = [ 'label' => Yii::t('common', 'Logout') . ' (' . Yii::$app->user->identity->username . ')', 'url' => ['/site/logout'], 'linkOptions' => ['data-method' => 'post'] ]; } // add this line $menuItems[] = \common\widgets\LanguageSelector::getMenu(); echo Nav::widget([ 'options' => [ 'class' => 'navbar-nav navbar-right', ], 'items' => $menuItems, // add this line 'encodeLabels' => false, ]); ...
    Copy after login

    8. Open the page to view the effect

    Yii2 framework study notes (3) -- Language and internationalization

    The above are Yii2 framework study notes (3) - language and internationalization content. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Latest Issues
    Popular Recommendations
      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!