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 MATLAB卫星二体模型仿真
  • ¥15 怎么让数码管亮的同时让led执行流水灯代码
  • ¥20 SAP HANA SQL Script 。如何判断字段值包含某个字符串
  • ¥85 cmd批处理参数如果含有双引号,该如何传入?
  • ¥15 fx2n系列plc的自控成型机模拟
  • ¥15 时间序列LSTM模型归回预测代码问题
  • ¥50 使用CUDA如何高效的做并行化处理,是否可以多个分段同时进行匹配计算处理?目前数据传输速度有些慢,如何提高速度,使用gdrcopy是否可行?请给出具体意见。
  • ¥15 基于STM32,电机驱动模块为L298N,四路运放电磁传感器,三轮智能小车电磁组电磁循迹(两个电机,一个万向轮),如何通过环岛的原理及完整代码
  • ¥20 机器学习或深度学习问题?困扰了我一个世纪,晚来天欲雪,能饮一杯无?
  • ¥15 c语言数据结构高铁订票系统