如何在Twig中进行复数形式翻译?

13

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

我尝试使用了

{% trans %} translation_key{% endtrans %}

尝试无果后,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 %}

提前致谢。

5个回答

21

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

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>

Twig模板:

{{ 'some.translation.key'|transchoice(count) }}

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

这是筛选器的原型:

public function transchoice($message, $count, array $arguments = array(), $domain = "messages", $locale = null)

1
当您使用该键时,翻译系统会直接选择正确的复数形式。 - gagarine

12

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 %}

transchoice标签会自动从当前上下文中获取%count%变量,并将其传递给翻译器。该机制仅在您使用符合%var%模式的占位符时才起作用。


12

这个主题相当古老,但我建议您做类似于以下内容:

在您的messages.LOCALE.yml文件中

you.translaction.key: "{1}1 Comment|]1,Inf]%count% Comments"
在您的twig模板中
{% set count = 2 %}

{% transchoice count with {'%count%': count} %}you.translaction.key{% endtranschoice %}

祝福您,

西蒙


{% transchoice count %}你的翻译.key{% endtranschoice %}会做。 - Solomon Tesfaye
{% transchoice count %}你的翻译.key{% endtranschoice %}会做。 - undefined

0

带有一个额外参数的示例:

{{ 'label.policy_expires_in'|transchoice(expiresInDays, {}, 'VopInsPolicyBundle') }}

-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 %}

7
这是一个黑客攻击。尼古拉·彼得坎斯基提供了攻击方法。 - gagarine
完全由您决定,但也许删除这个答案?它被普遍不喜欢 :) - James

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接