Login

russian pluralize filter

Author:
naprasno
Posted:
September 3, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

it works like an original "pluralize" filter, but it need argument with 3 parts, splitted by comma.

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months 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

#

Please login first before commenting.