2
0

internationalization.txt 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819
  1. ====================
  2. Internationalization
  3. ====================
  4. Overview
  5. ========
  6. The goal of internationalization is to allow a single Web application to offer
  7. its content and functionality in multiple languages and locales.
  8. For text translations, you, the Django developer, can accomplish this goal by
  9. adding a minimal amount of hooks to your Python and templates. These hooks
  10. are called **translation strings**. They tell Django: "This text should be
  11. translated into the end user's language, if a translation for this text is
  12. available in that language." It's your responsibility to mark translatable
  13. strings; the system can only translate strings it knows about.
  14. Django takes care of using these hooks to translate Web apps, on the fly,
  15. according to users' language preferences.
  16. Specifying translation strings: In Python code
  17. ==============================================
  18. Standard translation
  19. --------------------
  20. Specify a translation string by using the function ``ugettext()``. It's
  21. convention to import this as a shorter alias, ``_``, to save typing.
  22. .. note::
  23. Python's standard library ``gettext`` module installs ``_()`` into the
  24. global namespace, as an alias for ``gettext()``. In Django, we have chosen
  25. not to follow this practice, for a couple of reasons:
  26. 1. For international character set (Unicode) support, ``ugettext()`` is
  27. more useful than ``gettext()``. Sometimes, you should be using
  28. ``ugettext_lazy()`` as the default translation method for a particular
  29. file. Without ``_()`` in the global namespace, the developer has to
  30. think about which is the most appropriate translation function.
  31. 2. The underscore character (``_``) is used to represent "the previous
  32. result" in Python's interactive shell and doctest tests. Installing a
  33. global ``_()`` function causes interference. Explicitly importing
  34. ``ugettext()`` as ``_()`` avoids this problem.
  35. .. highlightlang:: python
  36. In this example, the text ``"Welcome to my site."`` is marked as a translation
  37. string::
  38. from django.utils.translation import ugettext as _
  39. def my_view(request):
  40. output = _("Welcome to my site.")
  41. return HttpResponse(output)
  42. Obviously, you could code this without using the alias. This example is
  43. identical to the previous one::
  44. from django.utils.translation import ugettext
  45. def my_view(request):
  46. output = ugettext("Welcome to my site.")
  47. return HttpResponse(output)
  48. Translation works on computed values. This example is identical to the previous
  49. two::
  50. def my_view(request):
  51. words = ['Welcome', 'to', 'my', 'site.']
  52. output = _(' '.join(words))
  53. return HttpResponse(output)
  54. Translation works on variables. Again, here's an identical example::
  55. def my_view(request):
  56. sentence = 'Welcome to my site.'
  57. output = _(sentence)
  58. return HttpResponse(output)
  59. (The caveat with using variables or computed values, as in the previous two
  60. examples, is that Django's translation-string-detecting utility,
  61. ``django-admin.py makemessages``, won't be able to find these strings. More on
  62. ``makemessages`` later.)
  63. The strings you pass to ``_()`` or ``ugettext()`` can take placeholders,
  64. specified with Python's standard named-string interpolation syntax. Example::
  65. def my_view(request, m, d):
  66. output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
  67. return HttpResponse(output)
  68. This technique lets language-specific translations reorder the placeholder
  69. text. For example, an English translation may be ``"Today is November 26."``,
  70. while a Spanish translation may be ``"Hoy es 26 de Noviembre."`` -- with the
  71. the month and the day placeholders swapped.
  72. For this reason, you should use named-string interpolation (e.g., ``%(day)s``)
  73. instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
  74. have more than a single parameter. If you used positional interpolation,
  75. translations wouldn't be able to reorder placeholder text.
  76. .. _translator-comments:
  77. Comments for translators
  78. ------------------------
  79. .. versionadded:: 1.3
  80. If you would like to give translators hints about a translatable string, you
  81. can add a comment prefixed with the ``Translators`` keyword on the line
  82. preceding the string, e.g.::
  83. def my_view(request):
  84. # Translators: This message appears on the home page only
  85. output = ugettext("Welcome to my site.")
  86. This also works in templates with the :ttag:`comment` tag:
  87. .. code-block:: html+django
  88. {% comment %}Translators: This is a text of the base template {% endcomment %}
  89. The comment will then appear in the resulting .po file and should also be
  90. displayed by most translation tools.
  91. Marking strings as no-op
  92. ------------------------
  93. Use the function ``django.utils.translation.ugettext_noop()`` to mark a string
  94. as a translation string without translating it. The string is later translated
  95. from a variable.
  96. Use this if you have constant strings that should be stored in the source
  97. language because they are exchanged over systems or users -- such as strings in
  98. a database -- but should be translated at the last possible point in time, such
  99. as when the string is presented to the user.
  100. Pluralization
  101. -------------
  102. Use the function ``django.utils.translation.ungettext()`` to specify pluralized
  103. messages.
  104. ``ungettext`` takes three arguments: the singular translation string, the plural
  105. translation string and the number of objects.
  106. This function is useful when you need your Django application to be localizable
  107. to languages where the number and complexity of `plural forms
  108. <http://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is
  109. greater than the two forms used in English ('object' for the singular and
  110. 'objects' for all the cases where ``count`` is different from zero, irrespective
  111. of its value.)
  112. For example::
  113. from django.utils.translation import ungettext
  114. def hello_world(request, count):
  115. page = ungettext('there is %(count)d object', 'there are %(count)d objects', count) % {
  116. 'count': count,
  117. }
  118. return HttpResponse(page)
  119. In this example the number of objects is passed to the translation languages as
  120. the ``count`` variable.
  121. Lets see a slightly more complex usage example::
  122. from django.utils.translation import ungettext
  123. count = Report.objects.count()
  124. if count == 1:
  125. name = Report._meta.verbose_name
  126. else:
  127. name = Report._meta.verbose_name_plural
  128. text = ungettext(
  129. 'There is %(count)d %(name)s available.',
  130. 'There are %(count)d %(name)s available.',
  131. count
  132. ) % {
  133. 'count': count,
  134. 'name': name
  135. }
  136. Here we reuse localizable, hopefully already translated literals (contained in
  137. the ``verbose_name`` and ``verbose_name_plural`` model ``Meta`` options) for
  138. other parts of the sentence so all of it is consistently based on the
  139. cardinality of the elements at play.
  140. .. _pluralization-var-notes:
  141. .. note::
  142. When using this technique, make sure you use a single name for every
  143. extrapolated variable included in the literal. In the example above note how
  144. we used the ``name`` Python variable in both translation strings. This
  145. example would fail::
  146. from django.utils.translation import ungettext
  147. from myapp.models import Report
  148. count = Report.objects.count()
  149. d = {
  150. 'count': count,
  151. 'name': Report._meta.verbose_name,
  152. 'plural_name': Report._meta.verbose_name_plural
  153. }
  154. text = ungettext(
  155. 'There is %(count)d %(name)s available.',
  156. 'There are %(count)d %(plural_name)s available.',
  157. count
  158. ) % d
  159. You would get a ``a format specification for argument 'name', as in
  160. 'msgstr[0]', doesn't exist in 'msgid'`` error when running
  161. ``django-admin.py compilemessages``.
  162. .. _contextual-markers:
  163. Contextual markers
  164. ------------------
  165. .. versionadded:: 1.3
  166. Sometimes words have several meanings, such as ``"May"`` in English, which
  167. refers to a month name and to a verb. To enable translators to translate
  168. these words correctly in different contexts, you can use the
  169. ``django.utils.translation.pgettext()`` function, or the
  170. ``django.utils.translation.npgettext()`` function if the string needs
  171. pluralization. Both take a context string as the first variable.
  172. In the resulting .po file, the string will then appear as often as there are
  173. different contextual markers for the same string (the context will appear on
  174. the ``msgctxt`` line), allowing the translator to give a different translation
  175. for each of them.
  176. For example::
  177. from django.utils.translation import pgettext
  178. month = pgettext("month name", "May")
  179. will appear in the .po file as:
  180. .. code-block:: po
  181. msgctxt "month name"
  182. msgid "May"
  183. msgstr ""
  184. .. _lazy-translations:
  185. Lazy translation
  186. ----------------
  187. Use the function ``django.utils.translation.ugettext_lazy()`` to translate
  188. strings lazily -- when the value is accessed rather than when the
  189. ``ugettext_lazy()`` function is called.
  190. For example, to translate a model's ``help_text``, do the following::
  191. from django.utils.translation import ugettext_lazy
  192. class MyThing(models.Model):
  193. name = models.CharField(help_text=ugettext_lazy('This is the help text'))
  194. In this example, ``ugettext_lazy()`` stores a lazy reference to the string --
  195. not the actual translation. The translation itself will be done when the string
  196. is used in a string context, such as template rendering on the Django admin
  197. site.
  198. The result of a ``ugettext_lazy()`` call can be used wherever you would use a
  199. unicode string (an object with type ``unicode``) in Python. If you try to use
  200. it where a bytestring (a ``str`` object) is expected, things will not work as
  201. expected, since a ``ugettext_lazy()`` object doesn't know how to convert
  202. itself to a bytestring. You can't use a unicode string inside a bytestring,
  203. either, so this is consistent with normal Python behavior. For example::
  204. # This is fine: putting a unicode proxy into a unicode string.
  205. u"Hello %s" % ugettext_lazy("people")
  206. # This will not work, since you cannot insert a unicode object
  207. # into a bytestring (nor can you insert our unicode proxy there)
  208. "Hello %s" % ugettext_lazy("people")
  209. If you ever see output that looks like ``"hello
  210. <django.utils.functional...>"``, you have tried to insert the result of
  211. ``ugettext_lazy()`` into a bytestring. That's a bug in your code.
  212. If you don't like the verbose name ``ugettext_lazy``, you can just alias it as
  213. ``_`` (underscore), like so::
  214. from django.utils.translation import ugettext_lazy as _
  215. class MyThing(models.Model):
  216. name = models.CharField(help_text=_('This is the help text'))
  217. Always use lazy translations in :doc:`Django models </topics/db/models>`.
  218. Field names and table names should be marked for translation (otherwise, they
  219. won't be translated in the admin interface). This means writing explicit
  220. ``verbose_name`` and ``verbose_name_plural`` options in the ``Meta`` class,
  221. though, rather than relying on Django's default determination of
  222. ``verbose_name`` and ``verbose_name_plural`` by looking at the model's class
  223. name::
  224. from django.utils.translation import ugettext_lazy as _
  225. class MyThing(models.Model):
  226. name = models.CharField(_('name'), help_text=_('This is the help text'))
  227. class Meta:
  228. verbose_name = _('my thing')
  229. verbose_name_plural = _('mythings')
  230. Notes on model classes translation
  231. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  232. Your model classes may not only contain normal fields: you may have relations
  233. (with a ``ForeignKey`` field) or additional model methods you may use for
  234. columns in the Django admin site.
  235. If you have models with foreign keys and you use the Django admin site, you can
  236. provide translations for the relation itself by using the ``verbose_name``
  237. parameter on the ``ForeignKey`` object::
  238. class MyThing(models.Model):
  239. kind = models.ForeignKey(ThingKind, related_name='kinds',
  240. verbose_name=_('kind'))
  241. As you would do for the ``verbose_name`` and ``verbose_name_plural`` settings of
  242. a model Meta class, you should provide a lowercase verbose name text for the
  243. relation as Django will automatically titlecase it when required.
  244. For model methods, you can provide translations to Django and the admin site
  245. with the ``short_description`` parameter set on the corresponding method::
  246. class MyThing(models.Model):
  247. kind = models.ForeignKey(ThingKind, related_name='kinds',
  248. verbose_name=_('kind'))
  249. def is_mouse(self):
  250. return self.kind.type == MOUSE_TYPE
  251. is_mouse.short_description = _('Is it a mouse?')
  252. As always with model classes translations, don't forget to use the lazy
  253. translation method!
  254. Working with lazy translation objects
  255. -------------------------------------
  256. Using ``ugettext_lazy()`` and ``ungettext_lazy()`` to mark strings in models
  257. and utility functions is a common operation. When you're working with these
  258. objects elsewhere in your code, you should ensure that you don't accidentally
  259. convert them to strings, because they should be converted as late as possible
  260. (so that the correct locale is in effect). This necessitates the use of a
  261. couple of helper functions.
  262. Joining strings: string_concat()
  263. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  264. Standard Python string joins (``''.join([...])``) will not work on lists
  265. containing lazy translation objects. Instead, you can use
  266. ``django.utils.translation.string_concat()``, which creates a lazy object that
  267. concatenates its contents *and* converts them to strings only when the result
  268. is included in a string. For example::
  269. from django.utils.translation import string_concat
  270. ...
  271. name = ugettext_lazy(u'John Lennon')
  272. instrument = ugettext_lazy(u'guitar')
  273. result = string_concat(name, ': ', instrument)
  274. In this case, the lazy translations in ``result`` will only be converted to
  275. strings when ``result`` itself is used in a string (usually at template
  276. rendering time).
  277. The allow_lazy() decorator
  278. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  279. Django offers many utility functions (particularly in ``django.utils``) that
  280. take a string as their first argument and do something to that string. These
  281. functions are used by template filters as well as directly in other code.
  282. If you write your own similar functions and deal with translations, you'll
  283. face the problem of what to do when the first argument is a lazy translation
  284. object. You don't want to convert it to a string immediately, because you might
  285. be using this function outside of a view (and hence the current thread's locale
  286. setting will not be correct).
  287. For cases like this, use the ``django.utils.functional.allow_lazy()``
  288. decorator. It modifies the function so that *if* it's called with a lazy
  289. translation as the first argument, the function evaluation is delayed until it
  290. needs to be converted to a string.
  291. For example::
  292. from django.utils.functional import allow_lazy
  293. def fancy_utility_function(s, ...):
  294. # Do some conversion on string 's'
  295. ...
  296. fancy_utility_function = allow_lazy(fancy_utility_function, unicode)
  297. The ``allow_lazy()`` decorator takes, in addition to the function to decorate,
  298. a number of extra arguments (``*args``) specifying the type(s) that the
  299. original function can return. Usually, it's enough to include ``unicode`` here
  300. and ensure that your function returns only Unicode strings.
  301. Using this decorator means you can write your function and assume that the
  302. input is a proper string, then add support for lazy translation objects at the
  303. end.
  304. .. versionadded:: 1.3
  305. Localized names of languages
  306. ============================
  307. The ``get_language_info()`` function provides detailed information about
  308. languages::
  309. >>> from django.utils.translation import get_language_info
  310. >>> li = get_language_info('de')
  311. >>> print li['name'], li['name_local'], li['bidi']
  312. German Deutsch False
  313. The ``name`` and ``name_local`` attributes of the dictionary contain the name of
  314. the language in English and in the language itself, respectively. The ``bidi``
  315. attribute is True only for bi-directional languages.
  316. The source of the language information is the ``django.conf.locale`` module.
  317. Similar access to this information is available for template code. See below.
  318. .. _specifying-translation-strings-in-template-code:
  319. Specifying translation strings: In template code
  320. ================================================
  321. .. highlightlang:: html+django
  322. Translations in :doc:`Django templates </topics/templates>` uses two template
  323. tags and a slightly different syntax than in Python code. To give your template
  324. access to these tags, put ``{% load i18n %}`` toward the top of your template.
  325. ``trans`` template tag
  326. ----------------------
  327. The ``{% trans %}`` template tag translates either a constant string
  328. (enclosed in single or double quotes) or variable content::
  329. <title>{% trans "This is the title." %}</title>
  330. <title>{% trans myvar %}</title>
  331. If the ``noop`` option is present, variable lookup still takes place but the
  332. translation is skipped. This is useful when "stubbing out" content that will
  333. require translation in the future::
  334. <title>{% trans "myvar" noop %}</title>
  335. Internally, inline translations use an ``ugettext`` call.
  336. In case a template var (``myvar`` above) is passed to the tag, the tag will
  337. first resolve such variable to a string at run-time and then look up that
  338. string in the message catalogs.
  339. It's not possible to mix a template variable inside a string within ``{% trans
  340. %}``. If your translations require strings with variables (placeholders), use
  341. ``{% blocktrans %}`` instead.
  342. ``blocktrans`` template tag
  343. ---------------------------
  344. .. versionchanged:: 1.3
  345. New keyword argument format.
  346. Contrarily to the ``trans`` tag, the ``blocktrans`` tag allows you to mark
  347. complex sentences consisting of literals and variable content for translation
  348. by making use of placeholders::
  349. {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}
  350. To translate a template expression -- say, accessing object attributes or
  351. using template filters -- you need to bind the expression to a local variable
  352. for use within the translation block. Examples::
  353. {% blocktrans with amount=article.price %}
  354. That will cost $ {{ amount }}.
  355. {% endblocktrans %}
  356. {% blocktrans with myvar=value|filter %}
  357. This will have {{ myvar }} inside.
  358. {% endblocktrans %}
  359. If you need to bind more than one expression inside a ``blocktrans`` tag,
  360. separate the pieces with ``and``::
  361. {% blocktrans with book_t=book|title author_t=author|title %}
  362. This is {{ book_t }} by {{ author_t }}
  363. {% endblocktrans %}
  364. This tag also provides for pluralization. To use it:
  365. * Designate and bind a counter value with the name ``count``. This value will
  366. be the one used to select the right plural form.
  367. * Specify both the singular and plural forms separating them with the
  368. ``{% plural %}`` tag within the ``{% blocktrans %}`` and
  369. ``{% endblocktrans %}`` tags.
  370. An example::
  371. {% blocktrans count counter=list|length %}
  372. There is only one {{ name }} object.
  373. {% plural %}
  374. There are {{ counter }} {{ name }} objects.
  375. {% endblocktrans %}
  376. A more complex example::
  377. {% blocktrans with amount=article.price count years=i.length %}
  378. That will cost $ {{ amount }} per year.
  379. {% plural %}
  380. That will cost $ {{ amount }} per {{ years }} years.
  381. {% endblocktrans %}
  382. When you use both the pluralization feature and bind values to local variables
  383. in addition to the counter value, keep in mind that the ``blocktrans``
  384. construct is internally converted to an ``ungettext`` call. This means the
  385. same :ref:`notes regarding ungettext variables <pluralization-var-notes>`
  386. apply.
  387. .. note:: The previous more verbose format is still supported:
  388. ``{% blocktrans with book|title as book_t and author|title as author_t %}``
  389. Reverse URL lookups cannot be carried out within the ``blocktrans`` and should
  390. be retrieved (and stored) beforehand::
  391. {% url path.to.view arg arg2 as the_url %}
  392. {% blocktrans %}
  393. This is a URL: {{ the_url }}
  394. {% endblocktrans %}
  395. .. _template-translation-vars:
  396. Other tags
  397. ----------
  398. Each ``RequestContext`` has access to three translation-specific variables:
  399. * ``LANGUAGES`` is a list of tuples in which the first element is the
  400. :term:`language code` and the second is the language name (translated into
  401. the currently active locale).
  402. * ``LANGUAGE_CODE`` is the current user's preferred language, as a string.
  403. Example: ``en-us``. (See :ref:`how-django-discovers-language-preference`.)
  404. * ``LANGUAGE_BIDI`` is the current locale's direction. If True, it's a
  405. right-to-left language, e.g.: Hebrew, Arabic. If False it's a
  406. left-to-right language, e.g.: English, French, German etc.
  407. If you don't use the ``RequestContext`` extension, you can get those values with
  408. three tags::
  409. {% get_current_language as LANGUAGE_CODE %}
  410. {% get_available_languages as LANGUAGES %}
  411. {% get_current_language_bidi as LANGUAGE_BIDI %}
  412. These tags also require a ``{% load i18n %}``.
  413. Translation hooks are also available within any template block tag that accepts
  414. constant strings. In those cases, just use ``_()`` syntax to specify a
  415. translation string::
  416. {% some_special_tag _("Page not found") value|yesno:_("yes,no") %}
  417. In this case, both the tag and the filter will see the already-translated
  418. string, so they don't need to be aware of translations.
  419. .. note::
  420. In this example, the translation infrastructure will be passed the string
  421. ``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
  422. translated string will need to contain the comma so that the filter
  423. parsing code knows how to split up the arguments. For example, a German
  424. translator might translate the string ``"yes,no"`` as ``"ja,nein"``
  425. (keeping the comma intact).
  426. .. versionadded:: 1.3
  427. You can also retrieve information about any of the available languages using
  428. provided template tags and filters. To get information about a single language,
  429. use the ``{% get_language_info %}`` tag::
  430. {% get_language_info for LANGUAGE_CODE as lang %}
  431. {% get_language_info for "pl" as lang %}
  432. You can then access the information::
  433. Language code: {{ lang.code }}<br />
  434. Name of language: {{ lang.name_local }}<br />
  435. Name in English: {{ lang.name }}<br />
  436. Bi-directional: {{ lang.bidi }}
  437. You can also use the ``{% get_language_info_list %}`` template tag to retrieve
  438. information for a list of languages (e.g. active languages as specified in
  439. :setting:`LANGUAGES`). See :ref:`the section about the set_language redirect
  440. view <set_language-redirect-view>` for an example of how to display a language
  441. selector using ``{% get_language_info_list %}``.
  442. In addition to :setting:`LANGUAGES` style nested tuples,
  443. ``{% get_language_info_list %}`` supports simple lists of language codes.
  444. If you do this in your view:
  445. .. code-block:: python
  446. return render_to_response('mytemplate.html', {
  447. 'available_languages': ['en', 'es', 'fr'],
  448. }, RequestContext(request))
  449. you can iterate over those languages in the template::
  450. {% get_language_info_list for available_languages as langs %}
  451. {% for lang in langs %} ... {% endfor %}
  452. There are also simple filters available for convenience:
  453. * ``{{ LANGUAGE_CODE|language_name }}`` ("German")
  454. * ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
  455. * ``{{ LANGUAGE_CODE|bidi }}`` (False)
  456. .. _Django templates: ../templates_python/
  457. Specifying translation strings: In JavaScript code
  458. ==================================================
  459. .. highlightlang:: python
  460. Adding translations to JavaScript poses some problems:
  461. * JavaScript code doesn't have access to a ``gettext`` implementation.
  462. * JavaScript code doesn't have access to .po or .mo files; they need to be
  463. delivered by the server.
  464. * The translation catalogs for JavaScript should be kept as small as
  465. possible.
  466. Django provides an integrated solution for these problems: It passes the
  467. translations into JavaScript, so you can call ``gettext``, etc., from within
  468. JavaScript.
  469. .. _javascript_catalog-view:
  470. The ``javascript_catalog`` view
  471. -------------------------------
  472. .. module:: django.views.i18n
  473. .. function:: javascript_catalog(request, domain='djangojs', packages=None)
  474. The main solution to these problems is the :meth:`django.views.i18n.javascript_catalog`
  475. view, which sends out a JavaScript code library with functions that mimic the
  476. ``gettext`` interface, plus an array of translation strings. Those translation
  477. strings are taken from applications or Django core, according to what you
  478. specify in either the info_dict or the URL. Paths listed in
  479. :setting:`LOCALE_PATHS` are also included.
  480. You hook it up like this::
  481. js_info_dict = {
  482. 'packages': ('your.app.package',),
  483. }
  484. urlpatterns = patterns('',
  485. (r'^jsi18n/$', 'django.views.i18n.javascript_catalog', js_info_dict),
  486. )
  487. Each string in ``packages`` should be in Python dotted-package syntax (the
  488. same format as the strings in ``INSTALLED_APPS``) and should refer to a package
  489. that contains a ``locale`` directory. If you specify multiple packages, all
  490. those catalogs are merged into one catalog. This is useful if you have
  491. JavaScript that uses strings from different applications.
  492. The precedence of translations is such that the packages appearing later in the
  493. ``packages`` argument have higher precedence than the ones appearing at the
  494. beginning, this is important in the case of clashing translations for the same
  495. literal.
  496. By default, the view uses the ``djangojs`` gettext domain. This can be
  497. changed by altering the ``domain`` argument.
  498. You can make the view dynamic by putting the packages into the URL pattern::
  499. urlpatterns = patterns('',
  500. (r'^jsi18n/(?P<packages>\S+?)/$', 'django.views.i18n.javascript_catalog'),
  501. )
  502. With this, you specify the packages as a list of package names delimited by '+'
  503. signs in the URL. This is especially useful if your pages use code from
  504. different apps and this changes often and you don't want to pull in one big
  505. catalog file. As a security measure, these values can only be either
  506. ``django.conf`` or any package from the :setting:`INSTALLED_APPS` setting.
  507. The JavaScript translations found in the paths listed in the
  508. :setting:`LOCALE_PATHS` setting are also always included. To keep consistency
  509. with the translations lookup order algorithm used for Python and templates, the
  510. directories listed in :setting:`LOCALE_PATHS` have the highest precedence with
  511. the ones appearing first having higher precedence than the ones appearing
  512. later.
  513. .. versionchanged:: 1.3
  514. Directories listed in ``LOCALE_PATHS`` weren't included in the lookup
  515. algorithm until version 1.3.
  516. Using the JavaScript translation catalog
  517. ----------------------------------------
  518. .. highlightlang:: javascript
  519. To use the catalog, just pull in the dynamically generated script like this:
  520. .. code-block:: html+django
  521. <script type="text/javascript" src="{% url django.views.i18n.javascript_catalog %}"></script>
  522. This uses reverse URL lookup to find the URL of the JavaScript catalog view.
  523. When the catalog is loaded, your JavaScript code can use the standard
  524. ``gettext`` interface to access it::
  525. document.write(gettext('this is to be translated'));
  526. There is also an ``ngettext`` interface::
  527. var object_cnt = 1 // or 0, or 2, or 3, ...
  528. s = ngettext('literal for the singular case',
  529. 'literal for the plural case', object_cnt);
  530. and even a string interpolation function::
  531. function interpolate(fmt, obj, named);
  532. The interpolation syntax is borrowed from Python, so the ``interpolate``
  533. function supports both positional and named interpolation:
  534. * Positional interpolation: ``obj`` contains a JavaScript Array object
  535. whose elements values are then sequentially interpolated in their
  536. corresponding ``fmt`` placeholders in the same order they appear.
  537. For example::
  538. fmts = ngettext('There is %s object. Remaining: %s',
  539. 'There are %s objects. Remaining: %s', 11);
  540. s = interpolate(fmts, [11, 20]);
  541. // s is 'There are 11 objects. Remaining: 20'
  542. * Named interpolation: This mode is selected by passing the optional
  543. boolean ``named`` parameter as true. ``obj`` contains a JavaScript
  544. object or associative array. For example::
  545. d = {
  546. count: 10,
  547. total: 50
  548. };
  549. fmts = ngettext('Total: %(total)s, there is %(count)s object',
  550. 'there are %(count)s of a total of %(total)s objects', d.count);
  551. s = interpolate(fmts, d, true);
  552. You shouldn't go over the top with string interpolation, though: this is still
  553. JavaScript, so the code has to make repeated regular-expression substitutions.
  554. This isn't as fast as string interpolation in Python, so keep it to those
  555. cases where you really need it (for example, in conjunction with ``ngettext``
  556. to produce proper pluralizations).
  557. .. _set_language-redirect-view:
  558. The ``set_language`` redirect view
  559. ==================================
  560. .. highlightlang:: python
  561. .. function:: set_language(request)
  562. As a convenience, Django comes with a view, :meth:`django.views.i18n.set_language`,
  563. that sets a user's language preference and redirects back to the previous page.
  564. Activate this view by adding the following line to your URLconf::
  565. (r'^i18n/', include('django.conf.urls.i18n')),
  566. (Note that this example makes the view available at ``/i18n/setlang/``.)
  567. The view expects to be called via the ``POST`` method, with a ``language``
  568. parameter set in request. If session support is enabled, the view
  569. saves the language choice in the user's session. Otherwise, it saves the
  570. language choice in a cookie that is by default named ``django_language``.
  571. (The name can be changed through the :setting:`LANGUAGE_COOKIE_NAME` setting.)
  572. After setting the language choice, Django redirects the user, following this
  573. algorithm:
  574. * Django looks for a ``next`` parameter in the ``POST`` data.
  575. * If that doesn't exist, or is empty, Django tries the URL in the
  576. ``Referrer`` header.
  577. * If that's empty -- say, if a user's browser suppresses that header --
  578. then the user will be redirected to ``/`` (the site root) as a fallback.
  579. Here's example HTML template code:
  580. .. code-block:: html+django
  581. <form action="/i18n/setlang/" method="post">
  582. {% csrf_token %}
  583. <input name="next" type="hidden" value="/next/page/" />
  584. <select name="language">
  585. {% get_language_info_list for LANGUAGES as languages %}
  586. {% for language in languages %}
  587. <option value="{{ language.code }}">{{ language.name_local }} ({{ language.code }})</option>
  588. {% endfor %}
  589. </select>
  590. <input type="submit" value="Go" />
  591. </form>