5 Django has full support for internationalization of text in code and templates.
11 The goal of internationalization is to allow a single Web application to offer
12 its content and functionality in multiple languages.
14 You, the Django developer, can accomplish this goal by adding a minimal amount
15 of hooks to your Python code and templates. These hooks are called
16 **translation strings**. They tell Django: "This text should be translated into
17 the end user's language, if a translation for this text is available in that
20 Django takes care of using these hooks to translate Web apps, on the fly,
21 according to users' language preferences.
23 Essentially, Django does two things:
25 * It lets developers and template authors specify which parts of their apps
26 should be translatable.
27 * It uses these hooks to translate Web apps for particular users according
28 to their language preferences.
30 How to internationalize your app: in three steps
31 ------------------------------------------------
33 1. Embed translation strings in your Python code and templates.
34 2. Get translations for those strings, in whichever languages you want to
36 3. Activate the locale middleware in your Django settings.
38 .. admonition:: Behind the scenes
40 Django's translation machinery uses the standard ``gettext`` module that
43 If you don't need internationalization
44 ======================================
46 Django's internationalization hooks are on by default, and that means there's a
47 bit of i18n-related overhead in certain places of the framework. If you don't
48 use internationalization, you should take the two seconds to set
49 ``USE_I18N = False`` in your settings file. If ``USE_I18N`` is set to
50 ``False``, then Django will make some optimizations so as not to load the
51 internationalization machinery. See the `documentation for USE_I18N`_.
53 You'll probably also want to remove ``'django.core.context_processors.i18n'``
54 from your ``TEMPLATE_CONTEXT_PROCESSORS`` setting.
56 .. _documentation for USE_I18N: ../settings/#use-i18n
58 How to specify translation strings
59 ==================================
61 Translation strings specify "This text should be translated." These strings can
62 appear in your Python code and templates. It's your responsibility to mark
63 translatable strings; the system can only translate strings it knows about.
71 Specify a translation string by using the function ``ugettext()``. It's
72 convention to import this as a shorter alias, ``_``, to save typing.
75 Python's standard library ``gettext`` module installs ``_()`` into the
76 global namespace, as an alias for ``gettext()``. In Django, we have chosen
77 not to follow this practice, for a couple of reasons:
79 1. For international character set (Unicode) support, ``ugettext()`` is
80 more useful than ``gettext()``. Sometimes, you should be using
81 ``ugettext_lazy()`` as the default translation method for a particular
82 file. Without ``_()`` in the global namespace, the developer has to
83 think about which is the most appropriate translation function.
85 2. The underscore character (``_``) is used to represent "the previous
86 result" in Python's interactive shell and doctest tests. Installing a
87 global ``_()`` function causes interference. Explicitly importing
88 ``ugettext()`` as ``_()`` avoids this problem.
90 In this example, the text ``"Welcome to my site."`` is marked as a translation
93 from django.utils.translation import ugettext as _
96 output = _("Welcome to my site.")
97 return HttpResponse(output)
99 Obviously, you could code this without using the alias. This example is
100 identical to the previous one::
102 from django.utils.translation import ugettext
104 def my_view(request):
105 output = ugettext("Welcome to my site.")
106 return HttpResponse(output)
108 Translation works on computed values. This example is identical to the previous
111 def my_view(request):
112 words = ['Welcome', 'to', 'my', 'site.']
113 output = _(' '.join(words))
114 return HttpResponse(output)
116 Translation works on variables. Again, here's an identical example::
118 def my_view(request):
119 sentence = 'Welcome to my site.'
121 return HttpResponse(output)
123 (The caveat with using variables or computed values, as in the previous two
124 examples, is that Django's translation-string-detecting utility,
125 ``make-messages.py``, won't be able to find these strings. More on
126 ``make-messages`` later.)
128 The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
129 specified with Python's standard named-string interpolation syntax. Example::
131 def my_view(request, n):
132 output = _('%(name)s is my name.') % {'name': n}
133 return HttpResponse(output)
135 This technique lets language-specific translations reorder the placeholder
136 text. For example, an English translation may be ``"Adrian is my name."``,
137 while a Spanish translation may be ``"Me llamo Adrian."`` -- with the
138 placeholder (the name) placed after the translated text instead of before it.
140 For this reason, you should use named-string interpolation (e.g., ``%(name)s``)
141 instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
142 have more than a single parameter. If you used positional interpolation,
143 translations wouldn't be able to reorder placeholder text.
145 Marking strings as no-op
146 ~~~~~~~~~~~~~~~~~~~~~~~~
148 Use the function ``django.utils.translation.ugettext_noop()`` to mark a string
149 as a translation string without translating it. The string is later translated
152 Use this if you have constant strings that should be stored in the source
153 language because they are exchanged over systems or users -- such as strings in
154 a database -- but should be translated at the last possible point in time, such
155 as when the string is presented to the user.
160 Use the function ``django.utils.translation.ugettext_lazy()`` to translate
161 strings lazily -- when the value is accessed rather than when the
162 ``ugettext_lazy()`` function is called.
164 For example, to translate a model's ``help_text``, do the following::
166 from django.utils.translation import ugettext_lazy
168 class MyThing(models.Model):
169 name = models.CharField(help_text=ugettext_lazy('This is the help text'))
171 In this example, ``ugettext_lazy()`` stores a lazy reference to the string --
172 not the actual translation. The translation itself will be done when the string
173 is used in a string context, such as template rendering on the Django admin site.
175 If you don't like the verbose name ``ugettext_lazy``, you can just alias it as
176 ``_`` (underscore), like so::
178 from django.utils.translation import ugettext_lazy as _
180 class MyThing(models.Model):
181 name = models.CharField(help_text=_('This is the help text'))
183 Always use lazy translations in `Django models`_. It's a good idea to add
184 translations for the field names and table names, too. This means writing
185 explicit ``verbose_name`` and ``verbose_name_plural`` options in the ``Meta``
188 from django.utils.translation import ugettext_lazy as _
190 class MyThing(models.Model):
191 name = models.CharField(_('name'), help_text=_('This is the help text'))
193 verbose_name = _('my thing')
194 verbose_name_plural = _('mythings')
196 .. _Django models: ../model-api/
201 Use the function ``django.utils.translation.ungettext()`` to specify pluralized
204 from django.utils.translation import ungettext
205 def hello_world(request, count):
206 page = ungettext('there is %(count)d object', 'there are %(count)d objects', count) % {
209 return HttpResponse(page)
211 ``ungettext`` takes three arguments: the singular translation string, the plural
212 translation string and the number of objects (which is passed to the
213 translation languages as the ``count`` variable).
218 Translations in `Django templates`_ uses two template tags and a slightly
219 different syntax than in Python code. To give your template access to these
220 tags, put ``{% load i18n %}`` toward the top of your template.
222 The ``{% trans %}`` template tag translates a constant string or a variable
225 <title>{% trans "This is the title." %}</title>
227 If you only want to mark a value for translation, but translate it later from a
228 variable, use the ``noop`` option::
230 <title>{% trans "value" noop %}</title>
232 It's not possible to use template variables in ``{% trans %}`` -- only constant
233 strings, in single or double quotes, are allowed. If your translations require
234 variables (placeholders), use ``{% blocktrans %}``. Example::
236 {% blocktrans %}This will have {{ value }} inside.{% endblocktrans %}
238 To translate a template expression -- say, using template filters -- you need
239 to bind the expression to a local variable for use within the translation
242 {% blocktrans with value|filter as myvar %}
243 This will have {{ myvar }} inside.
246 If you need to bind more than one expression inside a ``blocktrans`` tag,
247 separate the pieces with ``and``::
249 {% blocktrans with book|title as book_t and author|title as author_t %}
250 This is {{ book_t }} by {{ author_t }}
253 To pluralize, specify both the singular and plural forms with the
254 ``{% plural %}`` tag, which appears within ``{% blocktrans %}`` and
255 ``{% endblocktrans %}``. Example::
257 {% blocktrans count list|length as counter %}
258 There is only one {{ name }} object.
260 There are {{ counter }} {{ name }} objects.
263 Internally, all block and inline translations use the appropriate
264 ``ugettext`` / ``ungettext`` call.
266 Each ``RequestContext`` has access to two translation-specific variables:
268 * ``LANGUAGES`` is a list of tuples in which the first element is the
269 language code and the second is the language name (in that language).
270 * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
271 Example: ``en-us``. (See "How language preference is discovered", below.)
272 * ``LANGUAGE_BIDI`` is the current language's direction. If True, it's a
273 right-to-left language, e.g: Hebrew, Arabic. If False it's a
274 left-to-right language, e.g: English, French, German etc.
277 If you don't use the ``RequestContext`` extension, you can get those values with
280 {% get_current_language as LANGUAGE_CODE %}
281 {% get_available_languages as LANGUAGES %}
282 {% get_current_language_bidi as LANGUAGE_BIDI %}
284 These tags also require a ``{% load i18n %}``.
286 Translation hooks are also available within any template block tag that accepts
287 constant strings. In those cases, just use ``_()`` syntax to specify a
288 translation string. Example::
290 {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
292 In this case, both the tag and the filter will see the already-translated
293 string, so they don't need to be aware of translations.
295 .. _Django templates: ../templates_python/
297 Working with lazy translation objects
298 =====================================
300 Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
301 and utility functions is a common operation. When you're working with these
302 objects elsewhere in your code, you should ensure that you don't accidentally
303 convert them to strings, because they should be converted as late as possible
304 (so that the correct locale is in effect). This necessitates the use of a
305 couple of helper functions.
307 Joining strings: string_concat()
308 --------------------------------
310 Standard Python string joins (``''.join([...])``) will not work on lists
311 containing lazy translation objects. Instead, you can use
312 ``django.utils.translation.string_concat()``, which creates a lazy object that
313 concatenates its contents *and* converts them to strings only when the result
314 is included in a string. For example::
316 from django.utils.translation import string_concat
318 name = ugettext_lazy(u'John Lennon')
319 instrument = ugettext_lazy(u'guitar')
320 result = string_concat([name, ': ', instrument])
322 In this case, the lazy translations in ``result`` will only be converted to
323 strings when ``result`` itself is used in a string (usually at template
326 The allow_lazy() decorator
327 --------------------------
329 Django offers many utility functions (particularly in ``django.utils``) that
330 take a string as their first argument and do something to that string. These
331 functions are used by template filters as well as directly in other code.
333 If you write your own similar functions and deal with translations, you'll
334 face the problem of what to do when the first argument is a lazy translation
335 object. You don't want to convert it to a string immediately, because you might
336 be using this function outside of a view (and hence the current thread's locale
337 setting will not be correct).
339 For cases like this, use the ``django.utils.functional.allow_lazy()``
340 decorator. It modifies the function so that *if* it's called with a lazy
341 translation as the first argument, the function evaluation is delayed until it
342 needs to be converted to a string.
346 from django.utils.functional import allow_lazy
348 def fancy_utility_function(s, ...):
349 # Do some conversion on string 's'
351 fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
353 The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
354 a number of extra arguments (``*args``) specifying the type(s) that the
355 original function can return. Usually, it's enough to include ``unicode`` here
356 and ensure that your function returns only Unicode strings.
358 Using this decorator means you can write your function and assume that the
359 input is a proper string, then add support for lazy translation objects at the
362 How to create language files
363 ============================
365 Once you've tagged your strings for later translation, you need to write (or
366 obtain) the language translations themselves. Here's how that works.
368 .. admonition:: Locale restrictions
370 Django does not support localizing your application into a locale for
371 which Django itself has not been translated. In this case, it will ignore
372 your translation files. If you were to try this and Django supported it,
373 you would inevitably see a mixture of translated strings (from your
374 application) and English strings (from Django itself). If you want to
375 support a locale for your application that is not already part of
376 Django, you'll need to make at least a minimal translation of the Django
382 The first step is to create a **message file** for a new language. A message
383 file is a plain-text file, representing a single language, that contains all
384 available translation strings and how they should be represented in the given
385 language. Message files have a ``.po`` file extension.
387 Django comes with a tool, ``bin/make-messages.py``, that automates the creation
388 and upkeep of these files.
390 To create or update a message file, run this command::
392 bin/make-messages.py -l de
394 ...where ``de`` is the language code for the message file you want to create.
395 The language code, in this case, is in locale format. For example, it's
396 ``pt_BR`` for Brazilian Portugese and ``de_AT`` for Austrian German.
398 The script should be run from one of three places:
400 * The root ``django`` directory (not a Subversion checkout, but the one
401 that is linked-to via ``$PYTHONPATH`` or is located somewhere on that
403 * The root directory of your Django project.
404 * The root directory of your Django app.
406 The script runs over the entire Django source tree and pulls out all strings
407 marked for translation. It creates (or updates) a message file in the directory
408 ``conf/locale``. In the ``de`` example, the file will be
409 ``conf/locale/de/LC_MESSAGES/django.po``.
411 If run over your project source tree or your application source tree, it will
412 do the same, but the location of the locale directory is ``locale/LANG/LC_MESSAGES``
413 (note the missing ``conf`` prefix).
415 .. admonition:: No gettext?
417 If you don't have the ``gettext`` utilities installed, ``make-messages.py``
418 will create empty files. If that's the case, either install the ``gettext``
419 utilities or just copy the English message file
420 (``conf/locale/en/LC_MESSAGES/django.po``) and use it as a starting point;
421 it's just an empty translation file.
423 The format of ``.po`` files is straightforward. Each ``.po`` file contains a
424 small bit of metadata, such as the translation maintainer's contact
425 information, but the bulk of the file is a list of **messages** -- simple
426 mappings between translation strings and the actual translated text for the
429 For example, if your Django app contained a translation string for the text
430 ``"Welcome to my site."``, like so::
432 _("Welcome to my site.")
434 ...then ``make-messages.py`` will have created a ``.po`` file containing the
435 following snippet -- a message::
437 #: path/to/python/module.py:23
438 msgid "Welcome to my site."
443 * ``msgid`` is the translation string, which appears in the source. Don't
445 * ``msgstr`` is where you put the language-specific translation. It starts
446 out empty, so it's your responsibility to change it. Make sure you keep
447 the quotes around your translation.
448 * As a convenience, each message includes the filename and line number
449 from which the translation string was gleaned.
451 Long messages are a special case. There, the first string directly after the
452 ``msgstr`` (or ``msgid``) is an empty string. Then the content itself will be
453 written over the next few lines as one string per line. Those strings are
454 directly concatenated. Don't forget trailing spaces within the strings;
455 otherwise, they'll be tacked together without whitespace!
457 .. admonition:: Mind your charset
459 When creating a ``.po`` file with your favorite text editor, first edit
460 the charset line (search for ``"CHARSET"``) and set it to the charset
461 you'll be using to edit the content. Generally, utf-8 should work for most
462 languages, but ``gettext`` should handle any charset you throw at it.
464 To reexamine all source code and templates for new translation strings and
465 update all message files for **all** languages, run this::
469 Compiling message files
470 -----------------------
472 After you create your message file -- and each time you make changes to it --
473 you'll need to compile it into a more efficient form, for use by ``gettext``.
474 Do this with the ``bin/compile-messages.py`` utility.
476 This tool runs over all available ``.po`` files and creates ``.mo`` files,
477 which are binary files optimized for use by ``gettext``. In the same directory
478 from which you ran ``make-messages.py``, run ``compile-messages.py`` like
481 bin/compile-messages.py
483 That's it. Your translations are ready for use.
485 .. admonition:: A note to translators
487 If you've created a translation in a language Django doesn't yet support,
488 please let us know! See `Submitting and maintaining translations`_ for
491 .. _Submitting and maintaining translations: ../contributing/
493 How Django discovers language preference
494 ========================================
496 Once you've prepared your translations -- or, if you just want to use the
497 translations that come with Django -- you'll just need to activate translation
500 Behind the scenes, Django has a very flexible model of deciding which language
501 should be used -- installation-wide, for a particular user, or both.
503 To set an installation-wide language preference, set ``LANGUAGE_CODE`` in your
504 `settings file`_. Django uses this language as the default translation -- the
505 final attempt if no other translator finds a translation.
507 If all you want to do is run Django with your native language, and a language
508 file is available for your language, all you need to do is set
511 If you want to let each individual user specify which language he or she
512 prefers, use ``LocaleMiddleware``. ``LocaleMiddleware`` enables language
513 selection based on data from the request. It customizes content for each user.
515 To use ``LocaleMiddleware``, add ``'django.middleware.locale.LocaleMiddleware'``
516 to your ``MIDDLEWARE_CLASSES`` setting. Because middleware order matters, you
517 should follow these guidelines:
519 * Make sure it's one of the first middlewares installed.
520 * It should come after ``SessionMiddleware``, because ``LocaleMiddleware``
521 makes use of session data.
522 * If you use ``CacheMiddleware``, put ``LocaleMiddleware`` after it.
524 For example, your ``MIDDLEWARE_CLASSES`` might look like this::
526 MIDDLEWARE_CLASSES = (
527 'django.contrib.sessions.middleware.SessionMiddleware',
528 'django.middleware.locale.LocaleMiddleware',
529 'django.middleware.common.CommonMiddleware',
532 (For more on middleware, see the `middleware documentation`_.)
534 ``LocaleMiddleware`` tries to determine the user's language preference by
535 following this algorithm:
537 * First, it looks for a ``django_language`` key in the the current user's
539 * Failing that, it looks for a cookie called ``django_language``.
540 * Failing that, it looks at the ``Accept-Language`` HTTP header. This
541 header is sent by your browser and tells the server which language(s) you
542 prefer, in order by priority. Django tries each language in the header
543 until it finds one with available translations.
544 * Failing that, it uses the global ``LANGUAGE_CODE`` setting.
548 * In each of these places, the language preference is expected to be in the
549 standard language format, as a string. For example, Brazilian Portugese
551 * If a base language is available but the sublanguage specified is not,
552 Django uses the base language. For example, if a user specifies ``de-at``
553 (Austrian German) but Django only has ``de`` available, Django uses
555 * Only languages listed in the `LANGUAGES setting`_ can be selected. If
556 you want to restrict the language selection to a subset of provided
557 languages (because your application doesn't provide all those languages),
558 set ``LANGUAGES`` to a list of languages. For example::
562 ('en', _('English')),
565 This example restricts languages that are available for automatic
566 selection to German and English (and any sublanguage, like de-ch or
569 .. _LANGUAGES setting: ../settings/#languages
571 * If you define a custom ``LANGUAGES`` setting, as explained in the
572 previous bullet, it's OK to mark the languages as translation strings
573 -- but use a "dummy" ``ugettext()`` function, not the one in
574 ``django.utils.translation``. You should *never* import
575 ``django.utils.translation`` from within your settings file, because that
576 module in itself depends on the settings, and that would cause a circular
579 The solution is to use a "dummy" ``ugettext()`` function. Here's a sample
582 ugettext = lambda s: s
585 ('de', ugettext('German')),
586 ('en', ugettext('English')),
589 With this arrangement, ``make-messages.py`` will still find and mark
590 these strings for translation, but the translation won't happen at
591 runtime -- so you'll have to remember to wrap the languages in the *real*
592 ``ugettext()`` in any code that uses ``LANGUAGES`` at runtime.
594 * The ``LocaleMiddleware`` can only select languages for which there is a
595 Django-provided base translation. If you want to provide translations
596 for your application that aren't already in the set of translations
597 in Django's source tree, you'll want to provide at least basic
598 translations for that language. For example, Django uses technical
599 message IDs to translate date formats and time formats -- so you will
600 need at least those translations for the system to work correctly.
602 A good starting point is to copy the English ``.po`` file and to
603 translate at least the technical messages -- maybe the validator
606 Technical message IDs are easily recognized; they're all upper case. You
607 don't translate the message ID as with other messages, you provide the
608 correct local variant on the provided English value. For example, with
609 ``DATETIME_FORMAT`` (or ``DATE_FORMAT`` or ``TIME_FORMAT``), this would
610 be the format string that you want to use in your language. The format
611 is identical to the format strings used by the ``now`` template tag.
613 Once ``LocaleMiddleware`` determines the user's preference, it makes this
614 preference available as ``request.LANGUAGE_CODE`` for each `request object`_.
615 Feel free to read this value in your view code. Here's a simple example::
617 def hello_world(request, count):
618 if request.LANGUAGE_CODE == 'de-at':
619 return HttpResponse("You prefer to read Austrian German.")
621 return HttpResponse("You prefer to read another language.")
623 Note that, with static (middleware-less) translation, the language is in
624 ``settings.LANGUAGE_CODE``, while with dynamic (middleware) translation, it's
625 in ``request.LANGUAGE_CODE``.
627 .. _settings file: ../settings/
628 .. _middleware documentation: ../middleware/
629 .. _session: ../sessions/
630 .. _request object: ../request_response/#httprequest-objects
632 The ``set_language`` redirect view
633 ==================================
635 As a convenience, Django comes with a view, ``django.views.i18n.set_language``,
636 that sets a user's language preference and redirects back to the previous page.
638 Activate this view by adding the following line to your URLconf::
640 (r'^i18n/', include('django.conf.urls.i18n')),
642 (Note that this example makes the view available at ``/i18n/setlang/``.)
644 The view expects to be called via the ``GET`` method, with a ``language``
645 parameter set in the query string. If session support is enabled, the view
646 saves the language choice in the user's session. Otherwise, it saves the
647 language choice in a ``django_language`` cookie.
649 After setting the language choice, Django redirects the user, following this
652 * Django looks for a ``next`` parameter in the query string.
653 * If that doesn't exist, or is empty, Django tries the URL in the
655 * If that's empty -- say, if a user's browser suppresses that header --
656 then the user will be redirected to ``/`` (the site root) as a fallback.
658 Here's example HTML template code::
660 <form action="/i18n/setlang/" method="get">
661 <input name="next" type="hidden" value="/next/page/" />
662 <select name="language">
663 {% for lang in LANGUAGES %}
664 <option value="{{ lang.0 }}">{{ lang.1 }}</option>
667 <input type="submit" value="Go" />
670 Using translations in your own projects
671 =======================================
673 Django looks for translations by following this algorithm:
675 * First, it looks for a ``locale`` directory in the application directory
676 of the view that's being called. If it finds a translation for the
677 selected language, the translation will be installed.
678 * Next, it looks for a ``locale`` directory in the project directory. If it
679 finds a translation, the translation will be installed.
680 * Finally, it checks the base translation in ``django/conf/locale``.
682 This way, you can write applications that include their own translations, and
683 you can override base translations in your project path. Or, you can just build
684 a big project out of several apps and put all translations into one big project
685 message file. The choice is yours.
689 If you're using manually configured settings, as described in the
690 `settings documentation`_, the ``locale`` directory in the project
691 directory will not be examined, since Django loses the ability to work out
692 the location of the project directory. (Django normally uses the location
693 of the settings file to determine this, and a settings file doesn't exist
694 if you're manually configuring your settings.)
696 .. _settings documentation: ../settings/#using-settings-without-the-django-settings-module-environment-variable
698 All message file repositories are structured the same way. They are:
700 * ``$APPPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
701 * ``$PROJECTPATH/locale/<language>/LC_MESSAGES/django.(po|mo)``
702 * All paths listed in ``LOCALE_PATHS`` in your settings file are
703 searched in that order for ``<language>/LC_MESSAGES/django.(po|mo)``
704 * ``$PYTHONPATH/django/conf/locale/<language>/LC_MESSAGES/django.(po|mo)``
706 To create message files, you use the same ``make-messages.py`` tool as with the
707 Django message files. You only need to be in the right place -- in the directory
708 where either the ``conf/locale`` (in case of the source tree) or the ``locale/``
709 (in case of app messages or project messages) directory are located. And you
710 use the same ``compile-messages.py`` to produce the binary ``django.mo`` files that
711 are used by ``gettext``.
713 Application message files are a bit complicated to discover -- they need the
714 ``LocaleMiddleware``. If you don't use the middleware, only the Django message
715 files and project message files will be processed.
717 Finally, you should give some thought to the structure of your translation
718 files. If your applications need to be delivered to other users and will
719 be used in other projects, you might want to use app-specific translations.
720 But using app-specific translations and project translations could produce
721 weird problems with ``make-messages``: ``make-messages`` will traverse all
722 directories below the current path and so might put message IDs into the
723 project message file that are already in application message files.
725 The easiest way out is to store applications that are not part of the project
726 (and so carry their own translations) outside the project tree. That way,
727 ``make-messages`` on the project level will only translate strings that are
728 connected to your explicit project and not strings that are distributed
731 Translations and JavaScript
732 ===========================
734 Adding translations to JavaScript poses some problems:
736 * JavaScript code doesn't have access to a ``gettext`` implementation.
738 * JavaScript code doesn't have access to .po or .mo files; they need to be
739 delivered by the server.
741 * The translation catalogs for JavaScript should be kept as small as
744 Django provides an integrated solution for these problems: It passes the
745 translations into JavaScript, so you can call ``gettext``, etc., from within
748 The ``javascript_catalog`` view
749 -------------------------------
751 The main solution to these problems is the ``javascript_catalog`` view, which
752 sends out a JavaScript code library with functions that mimic the ``gettext``
753 interface, plus an array of translation strings. Those translation strings are
754 taken from the application, project or Django core, according to what you
755 specify in either the {{{info_dict}}} or the URL.
757 You hook it up like this::
760 'packages': ('your.app.package',),
763 urlpatterns = patterns('',
764 (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
767 Each string in ``packages`` should be in Python dotted-package syntax (the
768 same format as the strings in ``INSTALLED_APPS``) and should refer to a package
769 that contains a ``locale`` directory. If you specify multiple packages, all
770 those catalogs are merged into one catalog. This is useful if you have
771 JavaScript that uses strings from different applications.
773 You can make the view dynamic by putting the packages into the URL pattern::
775 urlpatterns = patterns('',
776 (r'^jsi18n/(?P<packages>\S+?)/$, 'django.views.i18n.javascript_catalog'),
779 With this, you specify the packages as a list of package names delimited by '+'
780 signs in the URL. This is especially useful if your pages use code from
781 different apps and this changes often and you don't want to pull in one big
782 catalog file. As a security measure, these values can only be either
783 ``django.conf`` or any package from the ``INSTALLED_APPS`` setting.
785 Using the JavaScript translation catalog
786 ----------------------------------------
788 To use the catalog, just pull in the dynamically generated script like this::
790 <script type="text/javascript" src="/path/to/jsi18n/"></script>
792 This is how the admin fetches the translation catalog from the server. When the
793 catalog is loaded, your JavaScript code can use the standard ``gettext``
794 interface to access it::
796 document.write(gettext('this is to be translated'));
798 There even is a ``ungettext`` interface and a string interpolation function::
803 s = interpolate(ungettext('this is %(count)s object', 'this are %(count)s objects', d.count), d);
805 The ``interpolate`` function supports both positional interpolation and named
806 interpolation. So the above could have been written as::
808 s = interpolate(ungettext('this is %s object', 'this are %s objects', 11), [11]);
810 The interpolation syntax is borrowed from Python. You shouldn't go over the top
811 with string interpolation, though: this is still JavaScript, so the code will
812 have to do repeated regular-expression substitutions. This isn't as fast as
813 string interpolation in Python, so keep it to those cases where you really
814 need it (for example, in conjunction with ``ungettext`` to produce proper
817 Creating JavaScript translation catalogs
818 ----------------------------------------
820 You create and update the translation catalogs the same way as the other Django
821 translation catalogs -- with the {{{make-messages.py}}} tool. The only
822 difference is you need to provide a ``-d djangojs`` parameter, like this::
824 make-messages.py -d djangojs -l de
826 This would create or update the translation catalog for JavaScript for German.
827 After updating translation catalogs, just run ``compile-messages.py`` the same
828 way as you do with normal Django translation catalogs.
830 Specialities of Django translation
831 ==================================
833 If you know ``gettext``, you might note these specialities in the way Django
836 * The string domain is ``django`` or ``djangojs``. The string domain is
837 used to differentiate between different programs that store their data
838 in a common message-file library (usually ``/usr/share/locale/``). The
839 ``django`` domain is used for python and template translation strings
840 and is loaded into the global translation catalogs. The ``djangojs``
841 domain is only used for JavaScript translation catalogs to make sure
842 that those are as small as possible.
843 * Django doesn't use ``xgettext`` alone. It uses Python wrappers around
844 ``xgettext`` and ``msgfmt``. That's mostly for convenience.