Reputation: 1746
I'm trying to get Jinja2 (and Django, via django-jinja
) to localize a number, eg. 123456
becomes 123,456
(or, of course, 123.456 depending on the locale). I've read every bit of documentation I can find on the subject, and can't find anything that actually works. Using standard DTL, one could just do:
{% localize on %}{{ some_number }}{% endlocalize %}
This works fine in my project using regular Django templates, but of course, doesn't work in Jinja2. I mention that this works fine because anything involving settings.py
such as USE_L10N
being False
can be ruled out.
I've tried the following, all based on documentation I've found:
{{ gettext("%(num)d", num=some_number) }}
- outputs number with no commas or localization.{% trans num=some_number %}{{ num }} {% endtrans %}
- as suggested by the django-jinja documentation - outputs number with no commas or localization.{{ _(some_number|string) }}
- outputs number with no commas or localization.{{ some_number|localize }}
- localize
is not a valid filter.So, how can I easily and properly localize a number using Jinja2?
Upvotes: 2
Views: 1430
Reputation: 861
Though it is an old question, I encountered the same found this solution feasible without lot of edits. Here is library that implements L10n for jinja2 templates. You could integrate it with your application like
TEMPLATES = [
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'extensions': [
'jdj_tags.extensions.DjangoStatic',
'jdj_tags.extensions.DjangoI18n',
'jdj_tags.extensions.DjangoL10n',
]
},
},
}
Upvotes: 0
Reputation: 1746
Figured it out. Jinja2 doesn't seem to handle localization on its own, but django-jinja
includes a built-in contrib that wraps django.contrib.humanize.templatetags
. According to the documentation for that, format localization is respected using the |intcomma
filter if L10n is enabled.
To use it, add django_jinja.contrib._humanize
to INSTALLED_APPS
in settings.py
:
INSTALLED_APPS += ('django_jinja.contrib._humanize',)
And then in templates, simply use the |intcomma
filter:
{{ some_number|intcomma }}
Upvotes: 1