Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pluralize a name in a template with jinja2?

If I have a template variable called num_countries, to pluralize with Django I could just write something like this:

countr{{ num_countries|pluralize:"y,ies" }}

Is there a way to do something like this with jinja2? (I do know this doesn't work in jinja2) What's the jinja2 alternative to this?

Thanks for any tip!

like image 663
craftApprentice Avatar asked Jul 30 '12 02:07

craftApprentice


2 Answers

Guy Adini's reply is definitely the way to go, though I think (or maybe I misused it) it is not exactly the same as pluralize filter in Django.

Hence this was my implementation (using decorator to register)

@app.template_filter('pluralize')
def pluralize(number, singular = '', plural = 's'):
    if number == 1:
        return singular
    else:
        return plural

This way, it is used exactly the same way (well, with parameters being passed in a slightly different way):

countr{{ num_countries|pluralize:("y","ies") }}
like image 92
Filipe Pina Avatar answered Sep 18 '22 13:09

Filipe Pina


Current Jinja versions have the i18n extension which adds decent translation and pluralization tags:

{% trans count=list|length %}
There is {{ count }} {{ name }} object.
{% pluralize %}
There are {{ count }} {{ name }} objects.
{% endtrans %}

You can use this even if you don't actually have multiple language versions - and if you ever add other languages you'll have a decent base which requires no changes (not all languages pluralize by adding an 's' and some even have multiple plural forms).

like image 33
ThiefMaster Avatar answered Sep 21 '22 13:09

ThiefMaster