When dealing with internationalization in JavaScript code, Django provides the JSONCatalog view which sends out a JavaScript code library with functions that mimic the gettext interface, plus an array of translation strings.
At first glance, it works well and everything is fine. But, because JSONCatalog view is generating JavaScript catalog dynamically on each and every request, it's adding an overhead that can be an issue with site growth.
That's what django-statici18n
is for:
Collecting JavaScript catalogs from each of your Django apps (and any other place you specify) into a single location that can easily be served in production.
The main website for django-statici18n
is
github.com/zyegfryed/django-statici18n where you can also file tickets.
django-statici18n
works with all the Django versions officially
supported by the Django project. At this time of writing, these are the
3.2 (LTS), 4.1, 4.2 series.
Use your favorite Python packaging tool to install
django-statici18n
from PyPI, e.g.:pip install django-statici18n
Add
'statici18n'
to yourINSTALLED_APPS
setting:INSTALLED_APPS = [ # ... 'statici18n', ]
Once you have translated and compiled your messages, use the
compilejsi18n
management command:python manage.py compilejsi18n
Add the django.core.context_processors.i18n context processor to the
context_processors
section for your backend in theTEMPLATES
setting - it should have already been set by Django:TEMPLATES = [ { # ... 'OPTIONS': { 'context_processors': { # ... 'django.template.context_processors.i18n', }, }, }, ]
Edit your template(s) and replace the dynamically generated script by the statically generated one:
<script src="{{ STATIC_URL }}jsi18n/{{ LANGUAGE_CODE }}/djangojs.js"></script>
Note
By default, the generated catalogs are stored to STATIC_ROOT/jsi18n
.
You can modify the output path and more options by tweaking
django-statici18n
settings.
(Optional)
The following step assumes you're using django.contrib.staticfiles.
- Edit your template(s) and use the provided template tag:
{% load statici18n %} <script src="{% statici18n LANGUAGE_CODE %}"></script>
- Or inline the JavaScript directly in your template:
{% load statici18n %} <script>{% inlinei18n LANGUAGE_CODE %}</script>