12.2. Localization JavaScript

urls.py:

>>> 
... from django.views.i18n import JavaScriptCatalog
...
... urlpatterns = [
...     path("jsi18n/", JavaScriptCatalog.as_view(), name="javascript-catalog"),
... ]

template:

<script src="{% url 'javascript-catalog' %}"></script>

12.2.1. gettext

  • translates strings

document.write(gettext("this is to be translated"))

12.2.2. ngettext

  • pluralize words and phrases

const objectCount = 1 // or 0, or 2, or 3, ...

const string = ngettext(
    'literal for the singular case',
    'literal for the plural case',
    objectCount
);

12.2.3. interpolate

  • dynamically populating a format string

const formats = ngettext(
  'There is %s object. Remaining: %s',
  'There are %s objects. Remaining: %s',
  11
);

const string = interpolate(formats, [11, 20]);
// string is 'There are 11 objects. Remaining: 20'
const data = {
  count: 10,
  total: 50
};

const formats = ngettext(
    'Total: %(total)s, there is %(count)s object',
    'there are %(count)s of a total of %(total)s objects',
    data.count
);

const string = interpolate(formats, data, true);

12.2.4. get_format

  • DATE_FORMAT

  • DATE_INPUT_FORMATS

  • DATETIME_FORMAT

  • DATETIME_INPUT_FORMATS

  • DECIMAL_SEPARATOR

  • FIRST_DAY_OF_WEEK

  • MONTH_DAY_FORMAT

  • NUMBER_GROUPING

  • SHORT_DATE_FORMAT

  • SHORT_DATETIME_FORMAT

  • THOUSAND_SEPARATOR

  • TIME_FORMAT

  • TIME_INPUT_FORMATS

  • YEAR_MONTH_FORMAT

document.write(get_format('DATE_FORMAT'));
// 'N j, Y'

12.2.5. pgettext

  • contextually translated word

document.write(pgettext("month name", "May"))

12.2.6. npgettext

  • pluralized contextually translated word

document.write(npgettext('group', 'party', 1));
// party
document.write(npgettext('group', 'party', 2));
// parties