Twig 对 0 个结果、1 个结果和多个结果使用特定值

Twig use specific value for 0 results, 1 result and multiple results

在使用 Symfony2 中的文章模块时,我必须显示某些内容被阅读了多少次。为了使 'sentence' 在语法上正确,我使用了下面的代码。

这很明显,但令我困扰的是我找不到更短、更简洁的方法。 是否有 article.getReads|length|displayresult('No results', '%d result', '%d results) 之类的东西可用,还是我必须自己制作?

{% if article.getReads|length == 0 %}Be the first one to read this!
{% else %}
  {{ article.getReads|length|number_format(0, ',', '.') }} 
  read{% if article.getReads|length != 1 %}s{% endif %}
{% endif %}

您可以使用 symfony2 复数翻译组件 here

例如,您可以像这样声明一个文件:

#src / Acme / DemoBundle / Resources / translations / messages.en.xliff

            <trans-unit id="11">
                <source>article.read</source>
                <target>{0} No results|{1} one result|[2,Inf] results</target>
            </trans-unit>

广告在树枝模板中使用如下:

{{ 'article.read'|transchoice(article.getReads|length) }}

希望对您有所帮助