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

While working on an article module in Symfony2, I have to display how many times something is read. To make the "sentence" grammatically correct, I used the code below.

It's obvious, but it waves me that I can't find a shorter, cleaner way. Is there something like article.getReads|length|displayresult('No results', '%d result', '%d results)

or do I need to do this myself?

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

      

+3


source to share


1 answer


You can use the symfony2 pluralization translate component as described here .

As an example, you can declare a file as:

#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>

      



The declaration uses it as shown in the branch template:

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

      

Hope for this help

+5


source







All Articles