Login

Plural templatetags if quantity > 1: return single else return plural

Author:
Natim
Posted:
December 7, 2009
Language:
HTML/template
Version:
Not specified
Score:
0 (after 0 ratings)

Regarding to a quantity, use the singular or the plural in two distincts template variables.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# -*- coding: utf-8 -*-

"""
Usage: {% plural quantity name_singular name_plural %}

This simple version only works with template variable since we will use blocktrans for strings.
"""

from django import template

register = template.Library()

class PluralNode(template.Node):
    def __init__(self, quantity, single, plural):
        self.quantity = template.Variable(quantity)
        self.single = template.Variable(single)
        self.plural = template.Variable(plural)

    def render(self, context):
        if self.quantity.resolve(context) > 1:
            return u'%s' % self.plural.resolve(context)
        else:
            return u'%s' % self.single.resolve(context)

@register.tag(name="plural")
def do_plural(parser, token):
    try:
        # split_contents() knows not to split quoted strings.
        tag_name, quantity, single, plural = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError, "%r tag requires exactly three arguments" % token.contents.split()[0]

    return PluralNode(quantity, single, plural)

More like this

  1. Bootstrap Accordian by Netplay4 7 years, 9 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 10 years, 9 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 10 years, 9 months ago
  4. Reusable form template with generic view by roldandvg 10 years, 10 months ago
  5. Pagination Django with Boostrap by guilegarcia 11 years ago

Comments

jdunck (on December 8, 2009):

What does this do that the pluralize filter doesn't?

#

Please login first before commenting.