doude4924 2015-06-26 06:49
浏览 80
已采纳

如何翻译Yii 2中的异常标题?

My Yii 2 application (based on app-basic scheme) still display English titles for exceptions like for example NotFoundHttpException, when user switches site language to non-English. Any other page element is correctly translated. Where titles of exceptions are stored? How can I fix this problem?

I tried searching through exception classes (NotFoundHttpException > HttpException > UserException > Exception) and found nothing. I browsed based translation files and found that /vendor/yiisoft/yii2/messages/ files have only The requested view "{name}" was not found. and Page not found. string for translations. There is no Not Found or Not Found ( strings to make correct translation of NotFoundHttpException (and others) exception's title in non-English languages.

Related readings:

  • 写回答

1条回答 默认 最新

  • doupinyan0186 2015-06-26 07:21
    关注

    There is no build-in translation of error or status code messages. One could implement a custom ErrorAction to translate the HTTP response codes. The documentation of yii\web\ErrorAction has the details of how to proceed.

    An alternative solution would be to use custom HttpExceptions and overwrite the getName function, but this would require you replicate all error classes you want to use.

    Example:

    Translation trait:

    namespace app\errors;
    
    use Yii;
    
    trait TranslateHttpCodes {
        public function getName()
        {
            return Yii::t('app', parent::getName());
        }
    }
    

    Custom error:

    namespace app\error;
    
    class NotFoundHttpException extends \yii\web\NotFoundHttpException
    {
       use TranslateHttpCodes;
    }
    

    As for error messages, the Yii error constructors take a message as an optional argument, so the message can be chosen freely.

    What this means is that one would have to put something like the following in the findModel controller method.

    throw new NotFoundHttpException(\Yii::t('app', 'The requested page does not exist.');
    

    The gii code generator doesn't do this automatically, even though it offers an --enableI18N command line flag. This might be considered a bug.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波