• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
xwlong
博客园    首页    新随笔    联系   管理    订阅  订阅
thinkphp5.0中英文切换

首先来看下它的配置:

// 是否开启多语言
'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',
];
?>

  

posted on 2017-06-18 11:52  xwlong  阅读(5039)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3