How to translate numbers in django translation?

Viewed 336

My head could not click how to translate numbers in django translation. It is not possible to translate by string id. I could print 2020 like:

{% translate '2' %}{% translate '0' %}{% translate '2' %}{% translate '0' %}

Obvioulsy, It is not the way. So, I am missing something. I would want something like:

{% translate "2020"|number %} # May be ?? It should be that easy right?

It should be that, translation from 0 to 9.

1 Answers

Django doesn't have this functionality (yet), but you can achieve the same by creating a custom template tag. You can read the whole documentation of creating the tag here, Custom template tags and filters.

By this way, you can translate Arabic Numerals (or anything) to any form, all you need is a mapper dict and a function that converts things by using the mapper dict.

We need to have a dict that has the source numerals as keys and target numeral as values. In this case, I assume you need to translate from Arabic numerals to nepali numerals

So, I have created a simple mapper using dict and converted the receiving value to something else using the translate_nepal_numeral(...) function.

from django import template
from django.template.defaultfilters import stringfilter

NUMBER_MAP = {
    "0": "०",
    "1": "१",
    "2": "२",
    # and so on

}

register = template.Library()


@register.filter()
@stringfilter
def translate_nepal_numeral(value):
    try:
        return "".join([NUMBER_MAP[char] for char in value])
    except KeyError:
        return value

Then in your template,

{% load custom_numerals %}

{{ "2010"|translate_nepal_numeral }}

Examples

In [3]: translate_nepal_numeral("2020")
Out[3]: '२०२०'

In [4]: translate_nepal_numeral("2120")
Out[4]: '२१२०'

In [5]: translate_nepal_numeral("2120a")
Out[5]: '2120a'

Notes

  1. If you are passing a non-numeral, this function will return the input
Related