20

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!

craftApprentice
  • 2,697
  • 17
  • 58
  • 86

4 Answers4

35

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") }}
Filipe Pina
  • 2,201
  • 23
  • 35
  • It seems that there's no need for semicolon when using a custom filter with arguments. At least there's no hint for it in jinja2's v.2.8 [documentation](http://jinja.pocoo.org/docs/dev/api/#writing-filters). I guess your example should be fixed like this: `countr{{ num_countries|pluralize("y","ies") }}` – vrs Dec 11 '16 at 14:02
  • 21, 31, 41 country, 11 countries – Suor Apr 23 '17 at 10:35
  • 1
    I would use `number % 100 in {1,21,31,41,51,61,71,81,91}` – Suor Apr 23 '17 at 10:37
  • In English, you definitely write '41 countries'. – Ross Burton Jan 25 '22 at 15:46
17

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).

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
5

According to Jinja's documentation, there is no built in filter which does what you want. You can easily design a custom filter to do that, however:

def my_plural(str, end_ptr = None, rep_ptr = ""):
    if end_ptr and str.endswith(end_ptr):
        return str[:-1*len(end_ptr)]+rep_ptr
    else:
        return str+'s'

and then register it in your environment:

environment.filters['myplural'] = my_plural

You can now use my_plural as a Jinja template.

Guy Adini
  • 5,188
  • 5
  • 32
  • 34
-6

You also want to check if the word is already plural. Here is my solution:

def pluralize(text):
    if text[-1:] !='s':
        return text+'s'
    else: 
        return text

Then register the tag to your environment (this can be applied to the Django templating engine too).

garbanzio
  • 846
  • 1
  • 7
  • 10