russian pluralize filter

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# -*- coding: utf-8 -*-

from django.template import Library, TemplateSyntaxError
from django.template.defaultfilters import stringfilter
register = Library()

@register.filter
@stringfilter
def rupluralize(value, arg):
    bits = arg.split(u',')   
    try:
        if str(value).endswith('1'):
            return bits[0]
        elif str(value)[-1:] in '234':
            return bits[1]
        else:
            return bits[2]
    except:
        raise TemplateSyntaxError
    return ''
rupluralize.is_safe = False

More like this

  1. Newforms field for decimals with a comma by jonasvp 5 years, 2 months ago
  2. format_thousands by cootetom 1 year, 10 months ago
  3. partial tag by bl4th3rsk1t3 3 years, 11 months ago
  4. Template tag to create a list from one or more variables and/or literals by davidchambers 2 years, 8 months ago
  5. Forms splitted in fieldsets by gustavo80br 5 years, 1 month ago

Comments

orlenko (on September 3, 2009):

This filter will not work for numbers that end in 11, 12, 13, and 14. For example:

  • 1 стул
  • 2-4 стула
  • 5-10 стульев
  • 11, стульев (your code will return "стул")
  • 12, 13, 14 стульев (your code will return "стула")
  • 111 стульев
  • 121 стул
  • 212 стульев
  • 222 стула

Something like this would work better:

def rupluralize(value, endings):
    try:
        endings = endings.split(',')
        if value % 100 in (11, 12, 13, 14):
            return endings[2]
        if value % 10 == 1:
            return endings[0]
        if value % 10 in (2, 3, 4):
            return endings[1]
        else:
            return endings[2]
    except:
        raise TemplateSyntaxError

#

buriy (on September 3, 2009):

you can find code that choose the correct form, by looking at any russian locale file, say, django.po: "Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;\n"

also you can use pytils module http://pyobject.ru/projects/pytils/ as a basis for your tags.

#

(Forgotten your password?)