Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

twig

symfony

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.

This works obvious but it botters me that I can't find a shorter, cleaner way. Is there something like article.getReads|length|displayresult('No results', '%d result', '%d results) available or do I have to make this on my own?

{% 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 %}
like image 872
Stefan Avatar asked Feb 02 '26 17:02

Stefan


1 Answers

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

As example you can declare a file like:

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

Ad use it as follow in the twig template:

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

Hope this help

like image 179
Matteo Avatar answered Feb 05 '26 07:02

Matteo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!