如何在Twig中进行多元化翻译?

gpe*_*ard 10 translation symfony twig

如何使用语言文件(messages.en.xliff)中的键翻译当前的硬编码文本?

我试着用

{% trans %} translation_key{% endtrans %}
Run Code Online (Sandbox Code Playgroud)

没有成功.Symfony返回此错误

消息必须是"ProjectEventsBundle:Default:show_event.html.twig"中的简单文本

500内部服务器错误 - Twig_Error_Syntax

{% transchoice count %}
{0} The current hardcoded text|{1} is attending|{2} are attending|]2,Inf] and %count% - 2 others are attending
{% endtranschoice %}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Nik*_*ski 16

我会使用这样的解决方案:

messages.en.xliff:

<trans-unit id="1">
    <source>some.translation.key</source>
    <target>{0} no.attendee|{1} one attendee|{2} two attendees|{3} three attendees|]3,Inf] many attendees</target>
</trans-unit>
Run Code Online (Sandbox Code Playgroud)

树枝模板:

{{ 'some.translation.key'|transchoice(count) }}
Run Code Online (Sandbox Code Playgroud)

如果你需要放一些参数,你应该将它们作为第二个参数传递.

这是过滤器的原型:

public function transchoice($message, $count, array $arguments = array(), $domain = "messages", $locale = null)
Run Code Online (Sandbox Code Playgroud)


ABC*_*ABC 9

Symfony文档中找到:

Symfony2提供专门的Twig标签(trans和transchoice)来帮助静态文本块的消息转换:

{% trans %}Hello %name%{% endtrans %}

{% transchoice count %}

{0} There are no apples|{1} There is one apple|]1,Inf] There are %count% apples

{% endtranschoice %}
Run Code Online (Sandbox Code Playgroud)

transchoice标签自动从当前上下文获取%count%变量并将其传递给翻译器.只有在%var%模式后使用占位符时,此机制才有效.


小智 9

这个主题已经很老了,但我建议你这样做:

在你的messages.LOCALE.yml中

you.translaction.key: "{1}1 Comment|]1,Inf]%count% Comments"
Run Code Online (Sandbox Code Playgroud)

在你的树枝模板中

{% set count = 2 %}

{% transchoice count with {'%count%': count} %}you.translaction.key{% endtranschoice %}
Run Code Online (Sandbox Code Playgroud)

干杯,

西蒙


gpe*_*ard -18

我找到了解决方案。它有点脏,但它正在工作。如果您发现更好的方法,请不要忘记发布。

    {% set noattendee %}{% trans %} no.attendee {% endtrans %}{% endset %}
    {% set oneattendee %}{% trans %} one.attendee {% endtrans %}{% endset %}
    {% set twoattendees %}{% trans %} two.attendees {% endtrans %}{% endset %}
    {% set treeattendees %}{% trans with {'%people%': people} %} tree.attendees {% endtrans %}{% endset %}
    {% set manyattendees %}{% trans with {'%people%': people} %} many.attendees {% endtrans %}{% endset %}

    {% transchoice count with {
        '%noattendee%': noattendee,
        '%oneattendee%': oneattendee,
        '%twoattendees%': twoattendees,
        '%treeattendees%': treeattendees,
        '%manyattendees%': manyattendees}
    %}
        {0}  %noattendee%|{1}  %oneattendee%|{2} %twoattendees%|{3} %treeattendees%|]3,Inf] %manyattendees%
    {% endtranschoice %}
Run Code Online (Sandbox Code Playgroud)

  • 这是一个黑客行为。尼古拉·佩特坎斯基 (Nikola Petkanski) 写下了前进的道路。 (7认同)