Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django plural for templates

How do I get django to realize that the singular form of countries is country and not countrie

like image 983
ApPeL Avatar asked Nov 15 '10 14:11

ApPeL


People also ask

How do you pluralize Django?

In Sendwithus you can use the pluralize filter to change the suffix of a word. Like Django's pluralize filter it returns a plural suffix if the first argument is an integer greater than 1 or a sequence with more than 1 item. If a plural suffix isn't specified pluralize defaults to 's'.

What does {% include %} do in Django?

From the documentation: {% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

Which characters are illegal in template variable names in Django?

Variable names consist of any combination of alphanumeric characters and the underscore ( "_" ) but may not start with an underscore, and may not be a number.

What is Autoescape in Django?

autoescape. Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag.


2 Answers

From the docs, if you have a template variable called num_countries, you could just write something like:

countr{{ num_countries|pluralize:"y,ies" }} 
like image 175
Spike Avatar answered Oct 14 '22 00:10

Spike


I know this question is specifically asked for templates, but for anyone (just like me) stumbling upon this question while searching for the solution in 'Python-side' Django

from django.template.defaultfilters import pluralize  def pluralize_countries(countries):     return 'countr{}'.format(pluralize(countries, 'y,ies') 

The pluralize function looks at the first parameter to see if it's plural or not. Let's assume the first parameter is always an array of some kind. So:

if len(countries) > 1:     # PLURAL! else:     # SINGLE! 

Than, it looks at the second parameter to see what to do if the first parameter is single or plural. A rough sketch of the pluralize code looks like this:

def pluralize(arr, options):     split_options = options.split(',')     if len(arr) > 1:         return split_options[1]     else:         return split_options[0] 

I know the pluralization is slightly more complex. But in a nutshell, this is what it does.

like image 26
Nebulosar Avatar answered Oct 13 '22 23:10

Nebulosar