首页 > 代码库 > thinkphp5.0中英文切换
thinkphp5.0中英文切换
thinkphp为我们提供了多语言类
首先来看下它的配置:
// 是否开启多语言
‘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();
var_dump($now_lang);
if($now_lang==‘zh-cn‘){
$now_lang=‘en-us‘;
}elseif($now_lang==‘en-us‘){
$now_lang=‘zh-cn‘;
}
var_dump($now_lang);
$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="http://www.mamicode.com/?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‘,
];
?>
<?phpnamespace 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;}}
?>
thinkphp5.0中英文切换