/
translation.txt
2157 lines (1570 loc) · 77.6 KB
/
translation.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
===========
Translation
===========
.. currentmodule:: django.utils.translation
Overview
========
In order to make a Django project translatable, you have to add a minimal
number of hooks to your Python code and templates. These hooks are called
:term:`translation strings <translation string>`. They tell Django: "This text
should be translated into the end user's language, if a translation for this
text is available in that language." It's your responsibility to mark
translatable strings; the system can only translate strings it knows about.
Django then provides utilities to extract the translation strings into a
:term:`message file`. This file is a convenient way for translators to provide
the equivalent of the translation strings in the target language. Once the
translators have filled in the message file, it must be compiled. This process
relies on the GNU gettext toolset.
Once this is done, Django takes care of translating Web apps on the fly in each
available language, according to users' language preferences.
Django's internationalization hooks are on by default, and that means there's a
bit of i18n-related overhead in certain places of the framework. If you don't
use internationalization, you should take the two seconds to set
:setting:`USE_I18N = False <USE_I18N>` in your settings file. Then Django will
make some optimizations so as not to load the internationalization machinery.
.. note::
There is also an independent but related :setting:`USE_L10N` setting that
controls if Django should implement format localization. See
:doc:`/topics/i18n/formatting` for more details.
.. note::
Make sure you've activated translation for your project (the fastest way is
to check if :setting:`MIDDLEWARE` includes
:mod:`django.middleware.locale.LocaleMiddleware`). If you haven't yet,
see :ref:`how-django-discovers-language-preference`.
Internationalization: in Python code
====================================
Standard translation
--------------------
Specify a translation string by using the function
:func:`~django.utils.translation.gettext`. It's convention to import this
as a shorter alias, ``_``, to save typing.
.. note::
Python's standard library ``gettext`` module installs ``_()`` into the
global namespace, as an alias for ``gettext()``. In Django, we have chosen
not to follow this practice, for a couple of reasons:
#. Sometimes, you should use :func:`~django.utils.translation.gettext_lazy`
as the default translation method for a particular file. Without ``_()``
in the global namespace, the developer has to think about which is the
most appropriate translation function.
#. The underscore character (``_``) is used to represent "the previous
result" in Python's interactive shell and doctest tests. Installing a
global ``_()`` function causes interference. Explicitly importing
``gettext()`` as ``_()`` avoids this problem.
.. admonition:: What functions may be aliased as ``_``?
Because of how ``xgettext`` (used by :djadmin:`makemessages`) works, only
functions that take a single string argument can be imported as ``_``:
* :func:`~django.utils.translation.gettext`
* :func:`~django.utils.translation.gettext_lazy`
In this example, the text ``"Welcome to my site."`` is marked as a translation
string::
from django.http import HttpResponse
from django.utils.translation import gettext as _
def my_view(request):
output = _("Welcome to my site.")
return HttpResponse(output)
You could code this without using the alias. This example is identical to the
previous one::
from django.http import HttpResponse
from django.utils.translation import gettext
def my_view(request):
output = gettext("Welcome to my site.")
return HttpResponse(output)
Translation works on computed values. This example is identical to the previous
two::
def my_view(request):
words = ['Welcome', 'to', 'my', 'site.']
output = _(' '.join(words))
return HttpResponse(output)
Translation works on variables. Again, here's an identical example::
def my_view(request):
sentence = 'Welcome to my site.'
output = _(sentence)
return HttpResponse(output)
(The caveat with using variables or computed values, as in the previous two
examples, is that Django's translation-string-detecting utility,
:djadmin:`django-admin makemessages <makemessages>`, won't be able to find
these strings. More on :djadmin:`makemessages` later.)
The strings you pass to ``_()`` or ``gettext()`` can take placeholders,
specified with Python's standard named-string interpolation syntax. Example::
def my_view(request, m, d):
output = _('Today is %(month)s %(day)s.') % {'month': m, 'day': d}
return HttpResponse(output)
This technique lets language-specific translations reorder the placeholder
text. For example, an English translation may be ``"Today is November 26."``,
while a Spanish translation may be ``"Hoy es 26 de noviembre."`` -- with the
month and the day placeholders swapped.
For this reason, you should use named-string interpolation (e.g., ``%(day)s``)
instead of positional interpolation (e.g., ``%s`` or ``%d``) whenever you
have more than a single parameter. If you used positional interpolation,
translations wouldn't be able to reorder placeholder text.
Since string extraction is done by the ``xgettext`` command, only syntaxes
supported by ``gettext`` are supported by Django. In particular, Python
:py:ref:`f-strings <f-strings>` are not yet supported by ``xgettext``, and
JavaScript template strings need ``gettext`` 0.21+.
.. _translator-comments:
Comments for translators
------------------------
If you would like to give translators hints about a translatable string, you
can add a comment prefixed with the ``Translators`` keyword on the line
preceding the string, e.g.::
def my_view(request):
# Translators: This message appears on the home page only
output = gettext("Welcome to my site.")
The comment will then appear in the resulting ``.po`` file associated with the
translatable construct located below it and should also be displayed by most
translation tools.
.. note:: Just for completeness, this is the corresponding fragment of the
resulting ``.po`` file:
.. code-block:: po
#. Translators: This message appears on the home page only
# path/to/python/file.py:123
msgid "Welcome to my site."
msgstr ""
This also works in templates. See :ref:`translator-comments-in-templates` for
more details.
Marking strings as no-op
------------------------
Use the function :func:`django.utils.translation.gettext_noop()` to mark a
string as a translation string without translating it. The string is later
translated from a variable.
Use this if you have constant strings that should be stored in the source
language because they are exchanged over systems or users -- such as strings
in a database -- but should be translated at the last possible point in time,
such as when the string is presented to the user.
Pluralization
-------------
Use the function :func:`django.utils.translation.ngettext()` to specify
pluralized messages.
``ngettext()`` takes three arguments: the singular translation string, the
plural translation string and the number of objects.
This function is useful when you need your Django application to be localizable
to languages where the number and complexity of `plural forms
<https://www.gnu.org/software/gettext/manual/gettext.html#Plural-forms>`_ is
greater than the two forms used in English ('object' for the singular and
'objects' for all the cases where ``count`` is different from one, irrespective
of its value.)
For example::
from django.http import HttpResponse
from django.utils.translation import ngettext
def hello_world(request, count):
page = ngettext(
'there is %(count)d object',
'there are %(count)d objects',
count,
) % {
'count': count,
}
return HttpResponse(page)
In this example the number of objects is passed to the translation
languages as the ``count`` variable.
Note that pluralization is complicated and works differently in each language.
Comparing ``count`` to 1 isn't always the correct rule. This code looks
sophisticated, but will produce incorrect results for some languages::
from django.utils.translation import ngettext
from myapp.models import Report
count = Report.objects.count()
if count == 1:
name = Report._meta.verbose_name
else:
name = Report._meta.verbose_name_plural
text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(name)s available.',
count,
) % {
'count': count,
'name': name
}
Don't try to implement your own singular-or-plural logic; it won't be correct.
In a case like this, consider something like the following::
text = ngettext(
'There is %(count)d %(name)s object available.',
'There are %(count)d %(name)s objects available.',
count,
) % {
'count': count,
'name': Report._meta.verbose_name,
}
.. _pluralization-var-notes:
.. note::
When using ``ngettext()``, make sure you use a single name for every
extrapolated variable included in the literal. In the examples above, note
how we used the ``name`` Python variable in both translation strings. This
example, besides being incorrect in some languages as noted above, would
fail::
text = ngettext(
'There is %(count)d %(name)s available.',
'There are %(count)d %(plural_name)s available.',
count,
) % {
'count': Report.objects.count(),
'name': Report._meta.verbose_name,
'plural_name': Report._meta.verbose_name_plural,
}
You would get an error when running :djadmin:`django-admin
compilemessages <compilemessages>`::
a format specification for argument 'name', as in 'msgstr[0]', doesn't exist in 'msgid'
.. versionchanged: 2.2.12
Added support for different plural equations in ``.po`` files.
.. _contextual-markers:
Contextual markers
------------------
Sometimes words have several meanings, such as ``"May"`` in English, which
refers to a month name and to a verb. To enable translators to translate
these words correctly in different contexts, you can use the
:func:`django.utils.translation.pgettext()` function, or the
:func:`django.utils.translation.npgettext()` function if the string needs
pluralization. Both take a context string as the first variable.
In the resulting ``.po`` file, the string will then appear as often as there are
different contextual markers for the same string (the context will appear on the
``msgctxt`` line), allowing the translator to give a different translation for
each of them.
For example::
from django.utils.translation import pgettext
month = pgettext("month name", "May")
or::
from django.db import models
from django.utils.translation import pgettext_lazy
class MyThing(models.Model):
name = models.CharField(help_text=pgettext_lazy(
'help text for MyThing model', 'This is the help text'))
will appear in the ``.po`` file as:
.. code-block:: po
msgctxt "month name"
msgid "May"
msgstr ""
Contextual markers are also supported by the :ttag:`translate` and
:ttag:`blocktranslate` template tags.
.. _lazy-translations:
Lazy translation
----------------
Use the lazy versions of translation functions in
:mod:`django.utils.translation` (easily recognizable by the ``lazy`` suffix in
their names) to translate strings lazily -- when the value is accessed rather
than when they're called.
These functions store a lazy reference to the string -- not the actual
translation. The translation itself will be done when the string is used in a
string context, such as in template rendering.
This is essential when calls to these functions are located in code paths that
are executed at module load time.
This is something that can easily happen when defining models, forms and
model forms, because Django implements these such that their fields are
actually class-level attributes. For that reason, make sure to use lazy
translations in the following cases:
Model fields and relationships ``verbose_name`` and ``help_text`` option values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For example, to translate the help text of the *name* field in the following
model, do the following::
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
You can mark names of :class:`~django.db.models.ForeignKey`,
:class:`~django.db.models.ManyToManyField` or
:class:`~django.db.models.OneToOneField` relationship as translatable by using
their :attr:`~django.db.models.Options.verbose_name` options::
class MyThing(models.Model):
kind = models.ForeignKey(
ThingKind,
on_delete=models.CASCADE,
related_name='kinds',
verbose_name=_('kind'),
)
Just like you would do in :attr:`~django.db.models.Options.verbose_name` you
should provide a lowercase verbose name text for the relation as Django will
automatically titlecase it when required.
Model verbose names values
~~~~~~~~~~~~~~~~~~~~~~~~~~
It is recommended to always provide explicit
:attr:`~django.db.models.Options.verbose_name` and
:attr:`~django.db.models.Options.verbose_name_plural` options rather than
relying on the fallback English-centric and somewhat naïve determination of
verbose names Django performs by looking at the model's class name::
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(_('name'), help_text=_('This is the help text'))
class Meta:
verbose_name = _('my thing')
verbose_name_plural = _('my things')
Model methods ``short_description`` attribute values
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For model methods, you can provide translations to Django and the admin site
with the ``short_description`` attribute::
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
kind = models.ForeignKey(
ThingKind,
on_delete=models.CASCADE,
related_name='kinds',
verbose_name=_('kind'),
)
def is_mouse(self):
return self.kind.type == MOUSE_TYPE
is_mouse.short_description = _('Is it a mouse?')
Working with lazy translation objects
-------------------------------------
The result of a ``gettext_lazy()`` call can be used wherever you would use a
string (a :class:`str` object) in other Django code, but it may not work with
arbitrary Python code. For example, the following won't work because the
`requests <https://pypi.org/project/requests/>`_ library doesn't handle
``gettext_lazy`` objects::
body = gettext_lazy("I \u2764 Django") # (Unicode :heart:)
requests.post('https://example.com/send', data={'body': body})
You can avoid such problems by casting ``gettext_lazy()`` objects to text
strings before passing them to non-Django code::
requests.post('https://example.com/send', data={'body': str(body)})
If you don't like the long ``gettext_lazy`` name, you can alias it as ``_``
(underscore), like so::
from django.db import models
from django.utils.translation import gettext_lazy as _
class MyThing(models.Model):
name = models.CharField(help_text=_('This is the help text'))
Using ``gettext_lazy()`` and ``ngettext_lazy()`` to mark strings in models
and utility functions is a common operation. When you're working with these
objects elsewhere in your code, you should ensure that you don't accidentally
convert them to strings, because they should be converted as late as possible
(so that the correct locale is in effect). This necessitates the use of the
helper function described next.
.. _lazy-plural-translations:
Lazy translations and plural
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When using lazy translation for a plural string (``n[p]gettext_lazy``), you
generally don't know the ``number`` argument at the time of the string
definition. Therefore, you are authorized to pass a key name instead of an
integer as the ``number`` argument. Then ``number`` will be looked up in the
dictionary under that key during string interpolation. Here's example::
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ngettext_lazy
class MyForm(forms.Form):
error_message = ngettext_lazy("You only provided %(num)d argument",
"You only provided %(num)d arguments", 'num')
def clean(self):
# ...
if error:
raise ValidationError(self.error_message % {'num': number})
If the string contains exactly one unnamed placeholder, you can interpolate
directly with the ``number`` argument::
class MyForm(forms.Form):
error_message = ngettext_lazy(
"You provided %d argument",
"You provided %d arguments",
)
def clean(self):
# ...
if error:
raise ValidationError(self.error_message % number)
Formatting strings: ``format_lazy()``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Python's :meth:`str.format()` method will not work when either the
``format_string`` or any of the arguments to :meth:`str.format()`
contains lazy translation objects. Instead, you can use
:func:`django.utils.text.format_lazy()`, which creates a lazy object
that runs the ``str.format()`` method only when the result is included
in a string. For example::
from django.utils.text import format_lazy
from django.utils.translation import gettext_lazy
...
name = gettext_lazy('John Lennon')
instrument = gettext_lazy('guitar')
result = format_lazy('{name}: {instrument}', name=name, instrument=instrument)
In this case, the lazy translations in ``result`` will only be converted to
strings when ``result`` itself is used in a string (usually at template
rendering time).
Other uses of lazy in delayed translations
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For any other case where you would like to delay the translation, but have to
pass the translatable string as argument to another function, you can wrap
this function inside a lazy call yourself. For example::
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _
mark_safe_lazy = lazy(mark_safe, str)
And then later::
lazy_string = mark_safe_lazy(_("<p>My <strong>string!</strong></p>"))
Localized names of languages
----------------------------
.. function:: get_language_info
The ``get_language_info()`` function provides detailed information about
languages::
>>> from django.utils.translation import activate, get_language_info
>>> activate('fr')
>>> li = get_language_info('de')
>>> print(li['name'], li['name_local'], li['name_translated'], li['bidi'])
German Deutsch Allemand False
The ``name``, ``name_local``, and ``name_translated`` attributes of the
dictionary contain the name of the language in English, in the language
itself, and in your current active language respectively. The ``bidi``
attribute is True only for bi-directional languages.
The source of the language information is the ``django.conf.locale`` module.
Similar access to this information is available for template code. See below.
.. _specifying-translation-strings-in-template-code:
Internationalization: in template code
======================================
.. highlight:: html+django
Translations in :doc:`Django templates </ref/templates/language>` uses two template
tags and a slightly different syntax than in Python code. To give your template
access to these tags, put ``{% load i18n %}`` toward the top of your template.
As with all template tags, this tag needs to be loaded in all templates which
use translations, even those templates that extend from other templates which
have already loaded the ``i18n`` tag.
.. warning::
Translated strings will not be escaped when rendered in a template.
This allows you to include HTML in translations, for example for emphasis,
but potentially dangerous characters (e.g. ``"``) will also be rendered
unchanged.
.. templatetag:: trans
.. templatetag:: translate
``translate`` template tag
--------------------------
The ``{% translate %}`` template tag translates either a constant string
(enclosed in single or double quotes) or variable content::
<title>{% translate "This is the title." %}</title>
<title>{% translate myvar %}</title>
If the ``noop`` option is present, variable lookup still takes place but the
translation is skipped. This is useful when "stubbing out" content that will
require translation in the future::
<title>{% translate "myvar" noop %}</title>
Internally, inline translations use an
:func:`~django.utils.translation.gettext` call.
In case a template var (``myvar`` above) is passed to the tag, the tag will
first resolve such variable to a string at run-time and then look up that
string in the message catalogs.
It's not possible to mix a template variable inside a string within
``{% translate %}``. If your translations require strings with variables
(placeholders), use :ttag:`{% blocktranslate %}<blocktranslate>` instead.
If you'd like to retrieve a translated string without displaying it, you can
use the following syntax::
{% translate "This is the title" as the_title %}
<title>{{ the_title }}</title>
<meta name="description" content="{{ the_title }}">
In practice you'll use this to get a string you can use in multiple places in a
template or so you can use the output as an argument for other template tags or
filters::
{% translate "starting point" as start %}
{% translate "end point" as end %}
{% translate "La Grande Boucle" as race %}
<h1>
<a href="/" title="{% blocktranslate %}Back to '{{ race }}' homepage{% endblocktranslate %}">{{ race }}</a>
</h1>
<p>
{% for stage in tour_stages %}
{% cycle start end %}: {{ stage }}{% if forloop.counter|divisibleby:2 %}<br>{% else %}, {% endif %}
{% endfor %}
</p>
``{% translate %}`` also supports :ref:`contextual markers<contextual-markers>`
using the ``context`` keyword:
.. code-block:: html+django
{% translate "May" context "month name" %}
.. versionchanged:: 3.1
The ``trans`` tag was renamed to ``translate``. The ``trans``
tag is still supported as an alias for backwards compatibility.
.. templatetag:: blocktrans
.. templatetag:: blocktranslate
``blocktranslate`` template tag
-------------------------------
Contrarily to the :ttag:`translate` tag, the ``blocktranslate`` tag allows you
to mark complex sentences consisting of literals and variable content for
translation by making use of placeholders::
{% blocktranslate %}This string will have {{ value }} inside.{% endblocktranslate %}
To translate a template expression -- say, accessing object attributes or
using template filters -- you need to bind the expression to a local variable
for use within the translation block. Examples::
{% blocktranslate with amount=article.price %}
That will cost $ {{ amount }}.
{% endblocktranslate %}
{% blocktranslate with myvar=value|filter %}
This will have {{ myvar }} inside.
{% endblocktranslate %}
You can use multiple expressions inside a single ``blocktranslate`` tag::
{% blocktranslate with book_t=book|title author_t=author|title %}
This is {{ book_t }} by {{ author_t }}
{% endblocktranslate %}
.. note:: The previous more verbose format is still supported:
``{% blocktranslate with book|title as book_t and author|title as author_t %}``
Other block tags (for example ``{% for %}`` or ``{% if %}``) are not allowed
inside a ``blocktranslate`` tag.
If resolving one of the block arguments fails, ``blocktranslate`` will fall
back to the default language by deactivating the currently active language
temporarily with the :func:`~django.utils.translation.deactivate_all`
function.
This tag also provides for pluralization. To use it:
* Designate and bind a counter value with the name ``count``. This value will
be the one used to select the right plural form.
* Specify both the singular and plural forms separating them with the
``{% plural %}`` tag within the ``{% blocktranslate %}`` and
``{% endblocktranslate %}`` tags.
An example::
{% blocktranslate count counter=list|length %}
There is only one {{ name }} object.
{% plural %}
There are {{ counter }} {{ name }} objects.
{% endblocktranslate %}
A more complex example::
{% blocktranslate with amount=article.price count years=i.length %}
That will cost $ {{ amount }} per year.
{% plural %}
That will cost $ {{ amount }} per {{ years }} years.
{% endblocktranslate %}
When you use both the pluralization feature and bind values to local variables
in addition to the counter value, keep in mind that the ``blocktranslate``
construct is internally converted to an ``ngettext`` call. This means the
same :ref:`notes regarding ngettext variables <pluralization-var-notes>`
apply.
Reverse URL lookups cannot be carried out within the ``blocktranslate`` and
should be retrieved (and stored) beforehand::
{% url 'path.to.view' arg arg2 as the_url %}
{% blocktranslate %}
This is a URL: {{ the_url }}
{% endblocktranslate %}
If you'd like to retrieve a translated string without displaying it, you can
use the following syntax::
{% blocktranslate asvar the_title %}The title is {{ title }}.{% endblocktranslate %}
<title>{{ the_title }}</title>
<meta name="description" content="{{ the_title }}">
In practice you'll use this to get a string you can use in multiple places in a
template or so you can use the output as an argument for other template tags or
filters.
``{% blocktranslate %}`` also supports :ref:`contextual
markers<contextual-markers>` using the ``context`` keyword:
.. code-block:: html+django
{% blocktranslate with name=user.username context "greeting" %}Hi {{ name }}{% endblocktranslate %}
Another feature ``{% blocktranslate %}`` supports is the ``trimmed`` option.
This option will remove newline characters from the beginning and the end of
the content of the ``{% blocktranslate %}`` tag, replace any whitespace at the
beginning and end of a line and merge all lines into one using a space
character to separate them. This is quite useful for indenting the content of a
``{% blocktranslate %}`` tag without having the indentation characters end up
in the corresponding entry in the PO file, which makes the translation process
easier.
For instance, the following ``{% blocktranslate %}`` tag::
{% blocktranslate trimmed %}
First sentence.
Second paragraph.
{% endblocktranslate %}
will result in the entry ``"First sentence. Second paragraph."`` in the PO file,
compared to ``"\n First sentence.\n Second paragraph.\n"``, if the
``trimmed`` option had not been specified.
.. versionchanged:: 3.1
The ``blocktrans`` tag was renamed to ``blocktranslate``. The ``blocktrans``
tag is still supported as an alias for backwards compatibility.
String literals passed to tags and filters
------------------------------------------
You can translate string literals passed as arguments to tags and filters
by using the familiar ``_()`` syntax::
{% some_tag _("Page not found") value|yesno:_("yes,no") %}
In this case, both the tag and the filter will see the translated string,
so they don't need to be aware of translations.
.. note::
In this example, the translation infrastructure will be passed the string
``"yes,no"``, not the individual strings ``"yes"`` and ``"no"``. The
translated string will need to contain the comma so that the filter
parsing code knows how to split up the arguments. For example, a German
translator might translate the string ``"yes,no"`` as ``"ja,nein"``
(keeping the comma intact).
.. _translator-comments-in-templates:
Comments for translators in templates
-------------------------------------
Just like with :ref:`Python code <translator-comments>`, these notes for
translators can be specified using comments, either with the :ttag:`comment`
tag:
.. code-block:: html+django
{% comment %}Translators: View verb{% endcomment %}
{% translate "View" %}
{% comment %}Translators: Short intro blurb{% endcomment %}
<p>{% blocktranslate %}A multiline translatable
literal.{% endblocktranslate %}</p>
or with the ``{#`` ... ``#}`` :ref:`one-line comment constructs <template-comments>`:
.. code-block:: html+django
{# Translators: Label of a button that triggers search #}
<button type="submit">{% translate "Go" %}</button>
{# Translators: This is a text of the base template #}
{% blocktranslate %}Ambiguous translatable block of text{% endblocktranslate %}
.. note:: Just for completeness, these are the corresponding fragments of the
resulting ``.po`` file:
.. code-block:: po
#. Translators: View verb
# path/to/template/file.html:10
msgid "View"
msgstr ""
#. Translators: Short intro blurb
# path/to/template/file.html:13
msgid ""
"A multiline translatable"
"literal."
msgstr ""
# ...
#. Translators: Label of a button that triggers search
# path/to/template/file.html:100
msgid "Go"
msgstr ""
#. Translators: This is a text of the base template
# path/to/template/file.html:103
msgid "Ambiguous translatable block of text"
msgstr ""
.. templatetag:: language
Switching language in templates
-------------------------------
If you want to select a language within a template, you can use the
``language`` template tag:
.. code-block:: html+django
{% load i18n %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<p>{% translate "Welcome to our page" %}</p>
{% language 'en' %}
{% get_current_language as LANGUAGE_CODE %}
<!-- Current language: {{ LANGUAGE_CODE }} -->
<p>{% translate "Welcome to our page" %}</p>
{% endlanguage %}
While the first occurrence of "Welcome to our page" uses the current language,
the second will always be in English.
.. _i18n-template-tags:
Other tags
----------
These tags also require a ``{% load i18n %}``.
.. templatetag:: get_available_languages
``get_available_languages``
~~~~~~~~~~~~~~~~~~~~~~~~~~~
``{% get_available_languages as LANGUAGES %}`` returns a list of tuples in
which the first element is the :term:`language code` and the second is the
language name (translated into the currently active locale).
.. templatetag:: get_current_language
``get_current_language``
~~~~~~~~~~~~~~~~~~~~~~~~
``{% get_current_language as LANGUAGE_CODE %}`` returns the current user's
preferred language as a string. Example: ``en-us``. See
:ref:`how-django-discovers-language-preference`.
.. templatetag:: get_current_language_bidi
``get_current_language_bidi``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
``{% get_current_language_bidi as LANGUAGE_BIDI %}`` returns the current
locale's direction. If ``True``, it's a right-to-left language, e.g. Hebrew,
Arabic. If ``False`` it's a left-to-right language, e.g. English, French,
German, etc.
.. _template-translation-vars:
``i18n`` context processor
~~~~~~~~~~~~~~~~~~~~~~~~~~
If you enable the :class:`django.template.context_processors.i18n` context
processor, then each ``RequestContext`` will have access to ``LANGUAGES``,
``LANGUAGE_CODE``, and ``LANGUAGE_BIDI`` as defined above.
.. templatetag:: get_language_info
``get_language_info``
~~~~~~~~~~~~~~~~~~~~~
You can also retrieve information about any of the available languages using
provided template tags and filters. To get information about a single language,
use the ``{% get_language_info %}`` tag::
{% get_language_info for LANGUAGE_CODE as lang %}
{% get_language_info for "pl" as lang %}
You can then access the information::
Language code: {{ lang.code }}<br>
Name of language: {{ lang.name_local }}<br>
Name in English: {{ lang.name }}<br>
Bi-directional: {{ lang.bidi }}
Name in the active language: {{ lang.name_translated }}
.. templatetag:: get_language_info_list
``get_language_info_list``
~~~~~~~~~~~~~~~~~~~~~~~~~~
You can also use the ``{% get_language_info_list %}`` template tag to retrieve
information for a list of languages (e.g. active languages as specified in
:setting:`LANGUAGES`). See :ref:`the section about the set_language redirect
view <set_language-redirect-view>` for an example of how to display a language
selector using ``{% get_language_info_list %}``.
In addition to :setting:`LANGUAGES` style list of tuples,
``{% get_language_info_list %}`` supports lists of language codes.
If you do this in your view:
.. code-block:: python
context = {'available_languages': ['en', 'es', 'fr']}
return render(request, 'mytemplate.html', context)
you can iterate over those languages in the template::
{% get_language_info_list for available_languages as langs %}
{% for lang in langs %} ... {% endfor %}
.. templatefilter:: language_name
.. templatefilter:: language_name_local
.. templatefilter:: language_bidi
.. templatefilter:: language_name_translated
Template filters
~~~~~~~~~~~~~~~~
There are also some filters available for convenience:
* ``{{ LANGUAGE_CODE|language_name }}`` ("German")
* ``{{ LANGUAGE_CODE|language_name_local }}`` ("Deutsch")
* ``{{ LANGUAGE_CODE|language_bidi }}`` (False)
* ``{{ LANGUAGE_CODE|language_name_translated }}`` ("německy", when active language is Czech)
Internationalization: in JavaScript code
========================================
.. highlight:: python
Adding translations to JavaScript poses some problems:
* JavaScript code doesn't have access to a ``gettext`` implementation.
* JavaScript code doesn't have access to ``.po`` or ``.mo`` files; they need to
be delivered by the server.
* The translation catalogs for JavaScript should be kept as small as
possible.
Django provides an integrated solution for these problems: It passes the
translations into JavaScript, so you can call ``gettext``, etc., from within
JavaScript.
The main solution to these problems is the following ``JavaScriptCatalog`` view,
which generates a JavaScript code library with functions that mimic the
``gettext`` interface, plus an array of translation strings.
The ``JavaScriptCatalog`` view
------------------------------
.. module:: django.views.i18n
.. class:: JavaScriptCatalog
A view that produces a JavaScript code library with functions that mimic
the ``gettext`` interface, plus an array of translation strings.
**Attributes**
.. attribute:: domain
Translation domain containing strings to add in the view output.
Defaults to ``'djangojs'``.
.. attribute:: packages