How to pluralize a name in a template with jinja2?

craftApprentice picture craftApprentice · Jul 30, 2012 · Viewed 8.3k times · Source

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!

Answer

Filipe Pina picture Filipe Pina · Mar 11, 2014

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") }}