---
title: "yii如何实现双语化"
author: "microcoder"
date: "2013-03-21T20:51:00Z"
tags: []
slug: "yii"
draft: false
lastmod: "2014-05-04T13:56:12Z"
id: 2059635
url: "https://microcoder.iteye.com/blog/2059635"
---

两种方式，可以自行考虑。一种是t(),另一种是模版整体替换

1.controller中定义初始化函数，根据路径判断所采用的语言

publicfunctioninit()  
{  
if([isset](http://www.php.net/isset)($\_GET\['hl'])&amp;&amp;'en'===$\_GET\['hl']){  
[setcookie](http://www.php.net/setcookie)("hl",'en\_us');  
$\_COOKIE\['hl']='en\_us';//cookie不能立刻生效  
}

elseif([isset](http://www.php.net/isset)($\_GET\['hl'])&amp;&amp;'zh'===$\_GET\['hl']){  
[unset](http://www.php.net/unset)($\_COOKIE\['hl']);  
[setcookie](http://www.php.net/setcookie)("hl","");  
}

if('en\_us'==$\_COOKIE\['hl']){  
Yii::app()-&gt;language='en\_us';  
}  
}

2.配置文件中添加：目的是让系统默认中文为系统语言

'sourceLanguage'=&amp;gt;'zh\_cn',

3.添加中文|English链接

echoCHtml::[link](http://www.php.net/link)('中文',[array](http://www.php.net/array)('','hl'=&gt;'zh')).'| '.CHtml::[link](http://www.php.net/link)('English',[array](http://www.php.net/array)('','hl'=&gt;'en'));//&lt;strong&gt;此处如果有朋友需要可以添加当前页面路径，具体如何我没有找到，有知道的朋友请留言&lt;/strong&gt;

4.Yii::t(’site’,'首页’) 一般用于view当中每个细节词条只要用这个包装后，以后都可以随时添加对应翻译。

同时在 protected/messages下面添加其他语言翻译，例如英语en\_us/site.php 其中（site对应之前调用的，yii是系统内部使用，一般不用，site可以换任意值）,内容：

return[array](http://www.php.net/array)(

'首页'=&gt;'Home'，//其他翻译以这个 source=&gt;target对应

);

5。另外一种是基于文件整体替换。也就是不同的语种用不同的模版

需要在views/controllerID/en\_us/example.php 这个文件名字跟原先模版一样，只是当语言在en\_us的时候调用这个，如何展示就看大家了。

转载地址[http://www.shotki.com/hezll/2009/12/yii%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%8F%8C%E8%AF%AD%E5%8C%96/](http://www.shotki.com/hezll/2009/12/yii%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E5%8F%8C%E8%AF%AD%E5%8C%96/)