• Yii2多语言


    背景: 如果项目有要求需要用到多语言的话,那么就需要引入语言包了。

    要添加语言包,需要现在config/main.php配置:

    'i18n' => [
                'translations' => [
                    'lang*' => [
                        'class' => 'yiii18nPhpMessageSource',
                    ]
                ],
            ],

    上面的 lang*表示可以加载lang+任意合法文件名的文件如:

    接下来是lang.php的内容:

    return [
        'title' => '',
        'ws_id' => '工号',
        'phone' => '手机',
        'next'  =>  '下一步',
        'cancel'    =>  '取消',
    
    ];

    调用方式如下:

    $this->title = Yii::t('lang_home', 'Title');

    另外,有时候会遇到一些比较特殊需要转化的字符串如   常量+变量+常量 (这边文章在2017年发表了) 2017就是变量,像这种要怎么做呢?

    我们先来看一下 Yii2 自带的函数 t 

        public static function t($category, $message, $params = [], $language = null)
        {
            if (static::$app !== null) {
                return static::$app->getI18n()->translate($category, $message, $params, $language ?: static::$app->language);
            }
    
            $placeholders = [];
            foreach ((array) $params as $name => $value) {
                $placeholders['{' . $name . '}'] = $value;
            }
    
            return ($placeholders === []) ? $message : strtr($message, $placeholders);
        }

    上面第三个参数是对参数的解析,什么参数呢?我们来看看下面的例子:

     'password {passwdMinLength}'
                                    => '密码长度必须大于或等于{passwdMinLength}',

    那么可以这么解析:

    $this->title = Yii::t('文件名', password',['passwdMinLength' => 5]);

    那么结果就是:密码长度必须大于或等于5

  • 相关阅读:
    I Show
    Centos上安装Google Authenticator
    linux 上mailx通过465端口发送邮件
    Win10 RDP CredSSP报错处理
    linux 双网卡代理上网
    English trip EM3-LP2B Teacher:Taylor
    【BZOJ1984】月下“毛景树”-树链剖分
    c++ 数据对拍器
    【BZOJ2157】旅游-树链剖分
    游戏-博弈论-树形DP
  • 原文地址:https://www.cnblogs.com/wilburxu/p/6544717.html
Copyright © 2020-2023  润新知