首先来看下它的配置:
// 是否开启多语言
'lang_switch_on' => true,
//语音列表
'lang_list' => ['zh-cn','en-us'],
// 获取当前选择语言的方法类
GetLang.php
<?php
namespace app\index\controller;
use think\Cookie;
use think\Lang;
use think\Request;
class GetLang{
public function get_lang(){
$lang = null;
if(input('?lang')){
$lang = input('lang');
}
if($lang==null){
if(Cookie::has('think_var')){
$lang = Cookie::get('think_var');
}else{
$lang = 'zh-cn';
}
}
$lang = Lang::range($lang);//设定当前语言
Lang::load(APP_PATH.DS.'index'.DS.'lang'.DS.$lang.EXT,$lang);//加载当前语言包
Cookie::set('think_var',$lang);
return $lang;
}
}
?>
// 显示效果的控制器类
Index.php
<?php
namespace app\index\controller;
use think\Controller;
class Index extends Controller
{
public function index(){
$lang = new \app\index\controller\GetLang;
$now_lang = $lang->get_lang();//获取当前语言
if($now_lang=='zh-cn'){
$now_lang='en-us';
}elseif($now_lang=='en-us'){
$now_lang='zh-cn';
}
$this->assign('set_lang',$now_lang);
return $this->fetch();
}
}
?>
// 视图页
index.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>{:lang('TITLE')}</title>
</head>
<body>
<a href="?lang={$set_lang}">{:lang('NOW_LANG')}</a>
</body>
</html>
//语言包文件
zh-cn.php
<?php
return [
'TITLE'=>'语言切换',
'NOW_LANG'=>'切换',
]
?>
en-us.php
<?php
return [
'TITLE'=>'Language switching',
'NOW_LANG'=>'Switch',
];
?>