Symfony 强制翻译成与当前语言不同的语言

Symfony forcing translation into different language than the current one

我将语言环境设置为一种语言。假设是德语 "de",我想将整个文本的 的一部分 翻译成不同的语言(例如 这发生在 100 年前 -> 这发生了或 100 Jahre)。为此,我正在尝试以下代码:

//this returns 'site.dates.years'
{% set yearsText = yearsCount|displayTimeDivisions() %} 

( {{ yearsCount }} {% trans with {'%content%': yearsText } from "messages" into "en" %}%content%{% endtrans %}

在使用 trans 方法后,我从 yearsText ('site.dates.years') 获取了字符串,而不是翻译后的内容。这甚至可以翻译还是我应该放弃它?

编辑:清除缓存

有时 Symfony 的缓存机制太强了。如果你首先在没有语言环境的情况下工作,然后将控制器和树枝修改为多语言环境,并且你还添加了一个新的消息文件,Symfony 加载所有新的 controller/twigs 但不知何故错过了有新的消息文件。一个简单的缓存清除,只在添加消息文件后完成一次(!),解决了这个问题。从此以后,您无需每次更改翻译时都清除缓存。

万不得已时请尝试此操作。如果这没有帮助,我建议您仔细阅读文档(此答案最后一行的 link):

app/console cache:clear --env=dev

您可以尝试其中的一项或全部 (!),无法判断哪里出了问题。

{{ yearsCount|trans }}
{{ 'site.dates.years'|trans }}

看看这些是否翻译。如果第二个是,则说明您以某种方式将变量设置错误。

如果没有,请在路线中传递_locale

defaults: { _controller: Bundle:Controller:action, _locale: de }

或者将其作为路由参数:

path: /a/path/{_locale}/whatever
  defaults: { _controller: Bundle:Controller:action }
  requirements:
      _locale: en|de

打印语言环境以确保它在 twig 中正确设置:

{{ app.request.locale }}
{{ app.request.getLocale() }}

如果语言环境打印正常但翻译仍然不起作用,那是因为 Symfony 没有找到标识符。转到翻译文件并检查它是否正确写入:

site:
  dates:
    years: Jahre

如果您在 messages.de.yml 中找到它,则可能是文件放置错误。加载程序搜索这些文件:

Symfony looks for message files (i.e. translations) in the following default locations:

  • the app/Resources/translations directory;
  • the app/Resources/MyAppBundle/translations directory;
  • the Resources/translations/ directory inside of any bundle.

如果摆弄这些文件没有产生结果,这是 config.yml 中的配置错误,或者许多重叠错误(以上所有?)对您不利。

这是所有 pain/info 翻译的来源,但您现在可能已经记住了每个段落:Symfony translations.

这按预期工作,您要翻译的是 %content%,而不是 site.dates.years。试试这个:

//this returns 'site.dates.years'
{% set yearsText = yearsCount|displayTimeDivisions() %} 

( {{ yearsCount }} {% trans from "messages" into "en" %}{{ yearsText }}{% endtrans %}

编辑 之前的建议不起作用,因为以这种方式使用 trans 仅适用于简单文本,不适用于变量。

这对我有用:

{{ yearsText | trans({}, 'messages', 'en') }}