【问题标题】:How do I get a translator object in the ExceptionController using symfony 3.4如何使用 symfony 3.4 在 ExceptionController 中获取翻译器对象
【发布时间】:2019-04-08 17:06:25
【问题描述】:

使用 symfony 3.4。当我需要在 Controller 中翻译某些内容时,我会执行以下操作:

$this->get('translator')->trans('termsAndConditions'),

当我想根据 http 状态代码翻译显示的错误消息时,如何在 ExceptionController 中执行此操作?来自命名空间Symfony\Bundle\FrameworkBundle\Controller 的控制器具有ControllerTrait 的特征和get() 方法。命名空间Symfony\Bundle\TwigBundle\Controller下的ExceptionController没有实现get()方法。

那么我怎样才能访问翻译器对象呢?

【问题讨论】:

    标签: php symfony exception internationalization


    【解决方案1】:

    我不建议对Symfony\Bundle\TwigBundle\Controller 进行任何更改,因为它会在您更新 symfony 本身时被覆盖。

    如果您希望根据 HTTP 状态代码显示自定义错误消息,请尝试 customizing the error pages。我相信您可以在这些自定义模板中简单地使用翻译器,如下所示:

    <div>
        {{ 'termsAndConditions'|trans }}
    </div>
    

    【讨论】:

    • 使用树枝捆绑包是唯一的方法吗?我不能以某种方式访问​​ ExceptionController 中的翻译器吗?
    • 好吧,ExceptionController 是 TwigBundle 本身的一部分,所以你不必添加任何东西。如果需要,您可以扩展 ExceptionController 并将翻译器注入到该扩展控制器。您将在我在答案中提供的链接中找到有关扩展控制器的信息。
    • 如果我像您在回答中建议的那样创建模板,它将始终加载英文版本。我如何告诉他为 *|trans 选择哪种语言?
    猜你喜欢
    • 1970-01-01
    • 2022-01-19
    • 2021-12-12
    • 1970-01-01
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多