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. math filter by itchyfingrs 3 years ago
  2. Audit word filter by shinyzhu 4 years, 2 months ago
  3. partition template filters by SmileyChris 6 years, 7 months ago
  4. "an" filter by SmileyChris 4 years, 11 months ago
  5. SmartyPants Filter by obeattie 7 years 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

#

(Forgotten your password?)