douan6931 2018-05-31 09:26
浏览 126
已采纳

Symfony 4不会翻译并始终显示英语默认值

I'm running Symfony 4 and I installed the translation system using

composer require symfony/translation

I've create two files in /translations:

  • messages.en.xlf
  • messages.es.xlf

Using php bin/console debug:translation es I also get the correct result:

----------- ---------- ------ ---------------------- ------------------------------- 
 State       Domain     Id     Message Preview (es)   Fallback Message Preview (en)  
----------- ---------- ------ ---------------------- ------------------------------- 
             messages   test   Value ES               Value EN                       
----------- ---------- ------ ---------------------- ------------------------------- 

The entries look like this:

<trans-unit id="test">
    <source>test</source>
    <target>Value EN</target>
</trans-unit>

and this:

<trans-unit id="test">
    <source>test</source>
    <target>Value ES</target>
</trans-unit>

In my controller I set the locale, which seems to work fine and is also represented in the Twig templates:

public function index(Request $request, TranslatorInterface $translator)
{
    $request->setLocale('es');
    // prints 'es'
    print $request->getLocale();
    return $this->render();
}

And in Twig:

{# prints 'es' #}
{{ app.request.locale }}

However, when I now run:

print $translator->trans('test');

or:

{{ 'test'|trans }}

I always get Value EN, which seems not correct as it should be Value ES.


I'm running Symfony 4.0 and cleared the cache multiple times - even deleted the whole folder.

The translations.yml looks like this:

framework:
    default_locale: '%locale%'
    translator:
        paths:
            - '%kernel.project_dir%/translations'
        fallbacks:
            - '%locale%'

And the services.ymllooks like this:

parameters:
    locale: 'en'
    locales: en|de|es

What am I missing here?

  • 写回答

1条回答 默认 最新

  • doutan4831 2018-05-31 09:32
    关注

    From official documentation

    To set the user's locale, you may want to create a custom event listener so that it's set before any other parts of the system (i.e. the translator) need it:

    And then (this is the part that explains your code behaviour)

    Setting the locale using $request->setLocale() in the controller is too late to affect the translator. Either set the locale via a listener (like above), the URL (see next) or call setLocale() directly on the translator service.

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

报告相同问题?

悬赏问题

  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥15 绘制多分类任务的roc曲线时只画出了一类的roc,其它的auc显示为nan
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?