Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template {% trans %} pluralization

According to this section in the Django docs I should use {% blocktrans %} for cases where I need to translate pluralizations. However, with an example like the following, isn't there something more convenient I can do?

{% blocktrans count video.views.count as views %}
The video has been viewed <span>{{ views }}</span> time
{% plural %}
The video has been viewed <span>{{ views }}</span> times
{% endblocktrans %}

I tried to do the following:

{% blocktrans %}time{% plural %}times{% endblocktrans %}

But it threw TemplateSyntaxError: 'blocktrans' doesn't allow other block tags (seen u'plural') inside it

like image 892
jmagnusson Avatar asked May 28 '10 14:05

jmagnusson


People also ask

How do I translate a template in Django?

In Django templates, the translate tag allows you to translate either a constant string or variable content. In fact, you can mark a string to be translated via {{ _("Hello World") }} or {% trans "Hello World" %} .

Which template tag is to be included for translating strings in a template?

The {% trans %} template tag The {% trans %} tag is useful for simple translation strings, but it cannot handle content for translation that includes variables.

How do I translate a placeholder in Django?

These functions store a lazy reference to the string – not the actual translation. The translation itself will be done when the string is used in a string context, such as in template rendering. This is essential when calls to these functions are located in code paths that are executed at module load time.

What is lazy text in Django?

Use the lazy versions of translation functions in django. utils. translation (easily recognizable by the lazy suffix in their names) to translate strings lazily – when the value is accessed rather than when they're called. These functions store a lazy reference to the string – not the actual translation.


1 Answers

You forgot the count variable as variable_name in the blocktrans tag

The value of that variable will be used to detect if it's plural or not.

{% blocktrans count variable as variable_name %}
    time
    {% plural %}
    {{ variable_name }} times
{% endblocktrans %}
like image 101
naw Avatar answered Oct 16 '22 14:10

naw