Django Integration

Django SDK offers a variety of template tags and filters that can be used in the Templates and Models. The following sections will provide a detailed description for every template tag and its options.

Functions

Template Tags

Template Filters

Django extensions

String Extensions (available throughout the application)

List Extensions (available throughout the application)

Date and DateTime Localization Extensions (available throughout the application)

Functions

ugettext

Translates message and returns it in a unicode string.

ugettext(label)

It’s convention to import this as a shorter alias, _, to save typing. In the following example "Hello World." is marked as translation string.

from django_tml import ugettext as _  
from django.http import HttpResponse

def my_view(request):  
    output = _("Hello World.")
    return HttpResponse(output)
Name Type Required Description
label string true The label to translate

ngettext

The ngettext function provides an interface to pluralize words and phrases. When page is rendered, this function returns the appropriate string based on number in a UTF-8 bytestring.

ngettext(singular, plural, number)  

Example:

var object_count = 3 // or 0, or 1, or 2, ...  
s = ngettext('There is {count} new message.',  
             'There are {count} new messages.', object_count);
Name Type Required Description
singular string true The singular translation string.
plural string true The plural translation string.
number int true The number based on which function decides which string to return, singular or plural.

ungettext

The ungettext function provides an interface to pluralize words and phrases. When page is rendered, this function returns the appropriate string based on number in a unicode string.

ungettext(singular, plural, number)  

Example:

var object_count = 1 // or 0, or 2, or 3, ...  
unicode_str = ungettext('There is {count} new message.',  
             'There are {count} new messages.', object_count);
Name Type Required Description
singular string true The singular translation string.
plural string true The plural translation string.
number int true The number based on which function decides which string form to return, singular or plural.

pgettext

Translates message given the description(context) and returns it in a unicode string.

pgettext(context, label)  

The pgettext function behaves like the Python variant (pgettext()), providing a contextually translated word:

pgettext('month name', 'May');  
pgettext('user name', 'May')  
Name Type Required Description
context string true The meaning of translating label.
label string true The label to translate.

tr

Main translation function available in the models and views.

tr(label, data=None, description=None, options=None)  

The tr function could be used in the variety of ways:

tr("secret key", description="technical term")  # omit context and options  
Name Type Required Description
label string true The meaning of translating label.
data dict false If label uses data or decoration tokens, the token values will be provided using this parameter.
description string false Description of the label that acts as a hint to the translator as well as contextualizes the key to be unique for the description.
options dict false Additional attributes.

Options:

  • nowrap - if set to true, content will not be decorated

activate

Activates Tml SDK for a given language for the current thread.

activate(language)  

The main reason for this helper function is to use Tml outside views and templates. Remember to switch back to original language, as activating a language is done on per-thread basis and such change will affect code running in the same thread:

from django_tml import activate, get_current_locale, tr

def welcome_translated(locale):  
    cur_locale = get_current_locale()
    try:
        activate(locale)
        text = tr('welcome')
    finally:
        activate(cur_locale)
    return text
Name Type Required Description
language string true Language code(locale) to activate e.g. 'ru', 'en', etc.

activate_source

Sets source of strings. Source is artificial separation of strings.

activate_source(source)  

Examples:

from django_tml import activate_source

activate_source("index")  
activate_source("navigation/sidebar")  
Name Type Required Description
source string true The name of the source e.g. 'index'

deactivate_source

Resets source of strings.

deactivate_source(source)  

Examples:

from django_tml import deactivate_source

deactivate("index")  
Name Type Required Description
source string true The name of the source e.g. 'index'

with_block_options

Context manager that. Overrides translation options during the block execution.

with_block_options(**options)  

Examples:

from django_tml import with_block_options, tr

with with_block_options(source='some/source'):  
    s = tr("hello world")
Name Type Required Description
options dict false Translation options

Options:

  • source - sets source of strings in your dashboard, source is artificial separation of strings
  • target_locale - used to set string to specific local which will not depend on default local, can be used for some text that you always want to see in specific locale.

Template Tags

tr

The tr tag allows you to mark complex sentences consisting of literals and variable (dynamic) content for translation by making use of tokens.

{% tr with foo="bar"... %} foo means {foo} {% endtr %}

Usage:

# 1. Horizontal translations
{% tr with count count=var|length %}
   This is {count||object,objects}.
{% endtr %}

# 2. vertical translations
{% tr count count=var|length %}
   There is {count} object.
{% plural %}
   There are {count} objects.
{% endtr %}

# 3. The "var as value" legacy format is still supported
{% tr with foo|filter as bar and baz|filter as boo %} ... {% endtr %}
{% tr count var|length as count %} ... {% endtr %}

# 4. Contextual markers
{% tr with foo|filter as bar context "greeting" %} ... {% endtr %}

Properties:

  • with -
  • count -
  • context -
  • as -
  • trimmed -
  • nowrap -

blocktrans

This tag is used for backward compatibility with Django translations. So if you started using TML at the middle stage of your development, then you probably have a lot of Django-based translations. In order to start using TML without friction, SDK monkeypatches blocktrans (as well as other Django translation functionality) template tag. On usage details you can refer to Django documentation.

trs

This tag is a helper for translating labels without tokens.

{% trs user.name %}
{% trs "Hello world" %}

Properties:

  • context -
  • as -
  • nowrap -

tmlopts

If you would select some TML options like target_locale or source you can use this template tag.

{% with tmlopts target_locale='en' %} ... {% endtmlopts %}
{% with tmlopts source='navigation' %} ...  {% endtmlopts %}

Options:

  • source -
  • target_locale -

source

A helper to set source just for some particular block(s) in template.

{% with source 'index' %} ... {% endsource %}

trlocale

A helper to set target_locale just for some particular block(s) in template.

{% with trlocale 'en' %} ... {% endtrlocale %}

Template Filters

trs

This filter is a helper for translating labels without tokens.

{{ "Hello world"|trs }}
{{ user.name|trs }}

# use it in conjunction with `tr` block tag
{% tr with user_address=user.address|trs %} ... {% endtr %}

trvalue

A value to render the token with.

{% tr with people=user_list|trvalue:'{$0}'
           people_options='{"limit": 2, "joiner": "or", "separator": ", "}' %}
   {people} joined the site.
{% endtr %}

trproperty

Use this filter if you wish to render the token by the hash key or object property.

{% tr with people=user_list|trproperty:'name'
           people_options='{"limit": 10, "joiner": "and", "separator": ", "}' %}
    {people} joined the site.
{% endtr %}

trattribute

Use this filter if you wish to render the token by hash key or object property.

{% tr with people=user_list|trattribute:'name'
           people_options='{"limit": 10, "joiner": "and", "separator": ", "}' %}
    {people} joined the site.
{% endtr %}

Django extensions

TmlModelChoiceField

  • Default widget: Select
  • Normalizes to: A model instance
  • extends django.forms.ModelChoiceField
  • generates translatable string representations for use in the field's choices

Allows the selection of a single model object, suitable for representing a foreign key.

from djagno_tml.fields import TmlModelChoiceField

assignee = TmlModelChoiceField(queryset=..., to_field_name="name")  

String Extensions


str tml_translate

Allows to translate any string from outside templates.

We don't offer the tr method here, since it is already implemented in the string. Instead we spell it out as tml_translate.

str.tml_translate(description='', data={}, options = {})

# or simply
str.tml_translate(data={}, options={})  

Example:

"Hello world".tml_translate()
"Invite".tml_translate(description="An invitation")
"Hello {user}".tml_translate(data={'user': 'Michael'})


str tml_trl

This method is similar to str tml_translate, but it disables inline translation mode.

str.tml_trl(description='', data={}, options = {})

# or simply
str.tml_trl(data={}, options={})  

Example:

"Hello world".tml_trl()
"Invite".tml_trl(description="An invitation")
"Hello {user}".tml_trl(data={'user': 'Michael'})

List Extensions


list tml_translate

Translates list elements.

list.tml_translate(description='', options = {})  

Example:

['Apple', 'Orange'].tml_translate()


list tml_translate_and_join

Translates the elements of the list and joins them together.

list.tml_translate_and_join(separator=', ', description='', options = {})  

Example:

['Apple', 'Orange'].tml_translate_and_join()


list tml_translate_sentence

Translates the elements of the list and joins them together.

list.tml_translate_sentence(description='', options = {})  

Example:

['Apples', 'Oranges', 'Bananas'].tml_translate_sentence(options={'joiner': 'and', 'separator': ', '})

# Яблоки, Апельсины и Бананы


list tml_translate_options

This method is mostly used for translating choices, model options. It translates the elements of the array and sub-arrays based on the data type.

list.tml_translate_options(description='', options = {})  

Example:

['Apples', 'Oranges', 'Bananas'].tml_translate_options()

# [["Apples", "Яблоки"], ["Oranges", "Апельсины"], ["Bananas", "Бананы"]]

DateTime Localization Extensions


datetime.date tml_translate

TML library provides a translation method for datetime.date and datetime.datetime objects that can be used to localize dates using TML syntax.

datetime.date.tml_translate(format, options)  

Example:

import datetime  
date = datetime.date(year=1989, month=10, day=7)  
date.tml_translate()  
date.tml_translate(':short_numeric')  
date.tml_translate(':date_time')  
date.tml_translate('%B %d, %Y')  

Parameters:

Name Type Default Description
format String :default An optional format for the date
options Hash Additional options for the translation, like :description and :with_leading_zero.

When the tml_translate method is called, it converts the standard datetime.date format to a more readable TML version that translators can change. For instance:

dummy_date.tml_translate('%B %d, %Y')  
# March 17, 2016

The function will map the standard notation to the following TML string:

{month_name} {days}, {years}

A Russian translator can then provide the following translation for the format:

{days} {month_name::gen}, {years}

Where the {days} token is followed by the month name in a Genitive language case, followed by the {years}.

The translated format will then be rendered as:

17 Марта, 2016

The library comes with a few presets for formats:

{
  ':default'               : '%m/%d/%Y',            # 07/4/2008
  ':short_numeric'         : '%m/%d',               # 07/4
  ':short_numeric_year'    : '%m/%d/%y',            # 07/4/08
  ':long_numeric'          : '%m/%d/%Y',            # 07/4/2008
  ':verbose'               : '%A, %B %d, %Y',       # Friday, July  4, 2008
  ':monthname'             : '%B %d',               # July 4
  ':monthname_year'        : '%B %d, %Y',           # July 4, 2008
  ':monthname_abbr'        : '%b %d',               # Jul 4
  ':monthname_abbr_year'   : '%b %d, %Y',           # Jul 4, 2008
  ':date_time'             : '%m/%d/%Y at %H:%M',   # 01/03/1010 at 5:30
}

And more custom presets can easily be added in the initialization:

TML = {  
   ...
   'localization': {
       'custom_date_formats': {
            'special': '%Y-%M-%d'
        }
    }
}

Now any time you pass :special as the format parameter, it will use the special format:

<%= dummy_date.tml_translate(:special) %>

# 2016-03-17

The following is the standard notation to token mapping:

{
  '%a': '{short_week_day_name}',
  '%A': '{week_day_name}',
  '%b': '{short_month_name}',
  '%B': '{month_name}',
  '%p': '{am_pm}',
  '%d': '{days}',
  '%e': '{day_of_month}',
  '%j': '{year_days}',
  '%m': '{months}',
  '%W': '{week_num}',
  '%w': '{week_days}',
  '%y': '{short_years}',
  '%Y': '{years}',
  '%l': '{trimed_hour}',
  '%H': '{full_hours}',
  '%I': '{short_hours}',
  '%M': '{minutes}',
  '%S': '{seconds}',
  '%s': '{since_epoch}'
}


datetime.date tml_trl

This method is just like the datetime.date tml_translate method, but it disables the inline translation mode.

dummy_date.tml_trl(':default')  
# March 17, 2016


datetime.datetime tml_translate

This method is similar to the datetime.datetime tml_translate method and provides additional elements for time mapping.

dummy_dt.tml_translate(':date_time')  
# 01/03/1010 at 5:30


datetime.datetime tml_trl

This method is just like the datetime.datetime tml_translate method, but it disables the inline translation mode.

dt.tml_trl(':date_time')  
# 01/03/1010 at 5:30