Blogger Information
Blog 55
fans 0
comment 0
visits 58842
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
TP语言包切换功能
南鸢离梦的博客
Original
1736 people have browsed it

一.配置

1.开启语言包功能

  1. 'lang_switch_on' => true,
  2. 2.支持的语言列表
  3. 'lang_list' => ['zh-cn','en-us'],

二.语言定义

  1. 3.语言定义
  2. 框架或模块目录\lang\zh-cn.php
  3. return [
  4. 'zhongwen'=>'中文',//表示模板内使用{:lang('zhongwen')}获得的字符在中文状态下显示为'中文'
  5. 'yingwen' =>'英文',
  6. ]
  7. 框架或模块目录\lang\en-us.php
  8. return [
  9. 'zhongwen'=>'chinese',//表示模板内使用{:lang('zhongwen')}获得的字符在英文状态下显示为'chinese'
  10. 'yingwen' =>'english',
  11. ]

三.自动侦测语言

  1. 路径:thinkphp\library\think\Lang.php修改函数detect()如下:
  2. public static function detect() {
  3. // 自动侦测设置获取语言选择
  4. $langSet = Config::get('default_lang');
  5. if (isset($_GET[self::$langDetectVar])) {
  6. // url中设置了语言变量
  7. $langSet = strtolower($_GET[self::$langDetectVar]);
  8. Cookie::set(self::$langCookieVar, $langSet, 3600);
  9. } elseif (Cookie::get(self::$langCookieVar)) {
  10. // 获取上次用户的选择
  11. $langSet = strtolower(Cookie::get(self::$langCookieVar));
  12. } elseif ($langSet) {
  13. // 获取默认语言
  14. Cookie::set(self::$langCookieVar, $langSet, 3600);
  15. } elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  16. // 自动侦测浏览器语言
  17. preg_match('/^([a-z\d\-]+)/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $matches);
  18. $langSet = strtolower($matches[1]);
  19. Cookie::set(self::$langCookieVar, $langSet, 3600);
  20. }
  21. if (empty(self::$allowLangList) || in_array($langSet, self::$allowLangList)) {
  22. // 合法的语言
  23. self::$range = $langSet;
  24. }
  25. }

四.控制器方法编写:

  1. public function changelang() {
  2. $lang=input('lang');
  3. switch ($lang) {
  4. case 'en':
  5. cookie('think_var', 'en-us');
  6. break;
  7. case 'zn':
  8. cookie('think_var', 'zh-cn');
  9. break;
  10. default:
  11. cookie('think_var','zh-cn');
  12. break;
  13. }
  14. }

五.html代码部分:

  1. <button class='n layui-btn' type="button" lang='en'>{:lang('yingwen')}</button>
  2. <button class='n layui-btn layui-btn-danger' lang='zn' type="button">{:lang('zhongwen')}</button>
  3. <script src="http://libs.baidu.com/jquery/1.10.2/jquery.js"></script>
  4. <script>
  5. $('.n').click(function(){
  6. var data={'lang':$(this).attr('lang')};
  7. $.get("{:url('Index/changelang')}",data,function(){
  8. location.reload();
  9. })
  10. })
  11. </script>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post