Yii2 framework学习笔记(三) — 语言与国际化

Yii2 framework学习笔记(三) — 语言与国际化国际化功能一般很少用到,但作为学习,还是有必要接触一下。国际化最常用到的方法是\Yii::t,官方文档如下t() publicstaticmethodTranslatesamessagetothespecifiedlanguage.Thisisashortcutmethodof yii\i18n\I18N::translate().

大家好,又见面了,我是你们的朋友全栈君。

国际化功能一般很少用到,但作为学习,还是有必要接触一下。

国际化最常用到的方法是\Yii::t,官方文档如下

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:

$username = 'Alexander';
echo \Yii::t('app', 'Hello, {username}!', ['username' => $username]);

Further formatting of message parameters is supported using the PHP intl extensions message formatter. See yii\i18n\I18N::translate() for more details.

public static string t ( $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-USen). If this is null, the current application language will be used.

return string

The translated message.

参数有4个,但常用到的是前两个。

第一个是组别,组别的定义放在config/main-local.php下。

Yii2默认用的是英语(en-US),现在添加中文支持(zh-CN)

在component下添加如下块

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

这段代码定义了一个名为common的组别,解析翻译文件用的是默认的类yii\i18n\PhpMessageSource,翻译文件放置在common/messages下,翻译文件是common.php。

根据配置,建立如下的目录结构

Yii2 framework学习笔记(三) -- 语言与国际化

翻译文件以数组的方式组织的,内容如下

<?php
return [
	'Signup' => '注册',
	'Login' => '登陆',
	'Logout' => '登出',
	'Home' => '首页',
	'Contact' => '反馈',
	'About' => '关于',
];

然后我们在layouts文件里做翻译,在/views/layouts/main.php里修改如下:

    $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']],
    ];

打开页面,看看是否生效。

遗憾的是,并不能生效。。。。。

Yii2 framework学习笔记(三) -- 语言与国际化

究其原因,是因为网站的根语言还是en-US,需要配置为zh-CN。

在common/config/main-local.php里,添加如下配置:

<?php
return [
   'language' => 'zh-CN',
   ...
];

再检查一下是否生效。

Yii2 framework学习笔记(三) -- 语言与国际化
可以看到翻译已经生效。

但用Yii::t方法的主要原因是要实现多语言,如果只是显示一种语言,还不如做hardcode(yii2框架实际做的也是hardcode的语言显示)

yii2没有提供现成的切换语言的控件,需要我们自己开发一个。

实现参考http://www.yiiframework.com/wiki/294/seo-conform-multilingual-urls-language-selector-widget-i18n/,并做了适度的简化,不做seo方面的考虑。

实现的主要思路是把用户选择的语言保存到cookie中,每次用户访问页面前,将语言设置为cookie中的值。为什么需要每次设置语言,原因如下

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’. 

大概意思就是如果不每次进行设值的话,系统将自己采用默认语言,一般是英语。

1.准备素材,国旗两面,放到frontend/web/image/下,命名为en.png和zh.png。

Yii2 framework学习笔记(三) -- 语言与国际化

2.在/common/config/main-local.php里配置可用的语言,供我们在控件中调用

<?php
return [
    'language' => 'zh-CN',

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

3.在/common/widgets/下新建一个php文件,命名为LanguageSelector.php,内容如下:

<?php

namespace common\widgets;

use Yii;
use yii\helpers\Html;
use yii\helpers\Url;

class LanguageSelector
{
	public static function getMenu()
	{
		$lang = Yii::$app->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 '<img src="' . $src . '" alt="' . $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[] = '<li>' . $link . '</li>';
		}
		return $menuItems;
	}
}

主要做的事情为:

  • 读取main-local.php中的配置项,形成数组。
  • 渲染菜单。
  • 为菜单中的按钮绑定事件,当点击时触发ajax请求,ajax顺利返回后刷新页面。
4.添加处理ajax的controller。在frontend/controllers下新建AjaxController.php,添加如下代码:
<?php

namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use common\components\SelectLanguageBehavior;
use yii\web\cookie;

class AjaxController extends Controller {
	public $layout = false;
	
	public function actionLang() {
		if (isset($_POST['_lang']))
		{
			$lang = SelectLanguageBehavior::getSelectedLanguage($_POST['_lang']);
			Yii::$app->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";
	}
	
}

其中重要的是把$layouts设为false,防止ajax返回渲染多余的东西。


5.增加一个动作(Behaviors),用来每次用户访问页面时修改语言。
在common/components下(如果没有该目录则新建目录),新建SelectLanguageBehavior.php,内容如下
<?phpnamespace common\components;use yii\base\Application;use yii\base\Behavior;use yii\web\cookie;use Yii;class SelectLanguageBehavior extends Behavior{	public function events()	{		return [				Application::EVENT_BEFORE_REQUEST => '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);	}}

6.将该动作绑定到系统中。

在common/config/main-local.php中添加as beginRequest项
<?phpreturn [	'language' => 'zh-CN',    'components' => [        ...    ],    ...	'as beginRequest' => [			'class' => 'common\components\SelectLanguageBehavior',	],];

7.将该控件添加到页面上。

在frontend/views/layouts/main.php里,添加代码显示我们的控件,因为控件中带html代码,还要防止它做转义处理
    ...    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,    ]);	...

8.打开页面查看效果

Yii2 framework学习笔记(三) -- 语言与国际化

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/131342.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月12日 下午2:46
下一篇 2022年6月12日 下午2:46


相关推荐

  • 绿联 NAS 私有云与 MiniMax 深度合作,首发开箱即用的 OpenClaw 龙虾应用

    绿联 NAS 私有云与 MiniMax 深度合作,首发开箱即用的 OpenClaw 龙虾应用

    2026年3月13日
    2
  • 网段划分和IP地址范围

    网段划分和IP地址范围将 192 8 8 0 192 8 8 256 分为尽可能 IP 数量接近的 4 个网段 这四个网段的子网掩码地址是多少 每一个子网可分配给主机的 IP 地址范围是多少 1 C 类地址 192 168 8 0 默认情况下的子网掩码是 255 255 255 0 首先我们要懂子网掩码这个东西 ipv4 的地址共 32 位的二进制数表示 那么 默认子网掩码十进制表示 255 255 255 0 那么二进制怎么表示 如下

    2026年3月26日
    3
  • 迭代和递归的理解和区别

    迭代和递归的理解和区别最近做一些题经常会碰到迭代的方法解的,或者递归解法,容易搞混,特在此整理一下一.递归:由例子引出,先看看递归的经典案例都有哪些1.斐波那契数列斐波纳契数列,又称黄金分割数列,指的是这样一个数列:1、1、2、3、5、8、13、21、……这个数列从第三项开始,每一项都等于前两项之和。2.阶乘n!=n*(n-1)*(n-2)*…*1(n>0)3.汉诺塔问…

    2022年5月3日
    38
  • 移动终端处理器构成和基带芯片概述「建议收藏」

    移动终端处理器构成和基带芯片概述

    2022年1月28日
    70
  • weblogic详解「建议收藏」

    weblogic详解「建议收藏」WebLogic中间件webspherejbossWebLogic介绍、安装1.1.1. 什么是中间件中间件(middleware)是基础软件的一大类,属于可复用软件的范畴.顾

    2022年8月1日
    9
  • derby数据库基础

    derby数据库基础一 Derby 数据库简介 1 Derby 的发展史及特性概述 nbsp nbsp nbsp nbsp nbsp nbsp nbsp Derby 是一个开源的 100 由 Java 开发的关系数据库 随着 Java 平台的普及 Derby 也收到了越来越多的关注 Derby 的前身是美国 IBM 公司的 ColudScape 2004 年 4 月 IBM 公司将 CloudScape 的数据库捐献给了 Apache 软件基金会 并将其更名为 Derby 接着 SUN 也为 Derby

    2026年3月17日
    1

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号