Ticket #2202: optional_arguments_to_pluralize.patch

File optional_arguments_to_pluralize.patch, 2.1 KB (added by Chris Beaven, 18 years ago)

Pluralize with optional arguments (tests and documentation included)

  • django/template/defaultfilters.py

     
    430430        return "%.1f MB" % (bytes / (1024 * 1024))
    431431    return "%.1f GB" % (bytes / (1024 * 1024 * 1024))
    432432
    433 def pluralize(value):
     433def pluralize(value, arg='s'):
    434434    "Returns 's' if the value is not 1, for '1 vote' vs. '2 votes'"
     435    if not ',' in arg:
     436        arg = arg + ','
     437    plural, single = arg.split(',', 1)
    435438    try:
    436439        if int(value) != 1:
    437             return 's'
     440            return plural
    438441    except ValueError: # invalid string that's not a number
    439442        pass
    440443    except TypeError: # value isn't a string or a number; maybe it's a list?
    441444        try:
    442445            if len(value) != 1:
    443                 return 's'
     446                return plural
    444447        except TypeError: # len() of unsized object
    445448            pass
    446     return ''
     449    return single
    447450
    448451def phone2numeric(value):
    449452    "Takes a phone number and converts it in to its numerical equivalent"
  • docs/templates.txt

     
    953953
    954954Returns ``'s'`` if the value is not 1.
    955955
    956 Example::
     956Use the optional argument to give an alternate plural. You can also add
     957the singlar alternative with a comma: ``"knives,knife"``
     958 
     959Examples::
    957960
    958961    You have {{ num_messages }} message{{ num_messages|pluralize }}.
     962   
     963    Managed by {{ bosses }} boss{{ bosses|pluralize:"es" }}.
     964   
     965    I know {{ female_count }} {{ female_count|pluralize:"women,woman" }}.
    959966
    960967pprint
    961968~~~~~~
  • tests/othertests/defaultfilters.py

     
    313313>>> pluralize(2)
    314314's'
    315315
     316>>> pluralize(2, 'es')
     317'es'
     318
     319>>> pluralize(1, 'men,man')
     320'man'
     321
     322>>> pluralize(5, 'men,man')
     323'men'
     324
    316325>>> phone2numeric('0800 flowers')
    317326'0800 3569377'
    318327
Back to Top