T and Internationalization

The object T is the language translator. It constitutes a single global instance of the WEB2PY class gluon.language.translator. All string constants (and only string constants) should be marked by T, for example:

Strings that are marked with t are identified by web2py as needing language translation and they will be translated when the code (in the model, controller, or view) is executed. If the string to be translated is not a constant but a variable, it will be added to the translation file at runtime (except on GAE) to be translated later.

The T object can also contain interpolated variables, for example:

1 a = T("hello %(name)s", dict(name= "'Massimo"))

The first string is translated according to the requested language file and the name variable is replaced independently of the language.

Concatenating translation strings is not a good idea; this is why web2py does not allow you to do:

1 T( "blah ") + name + K" blah") # invalid!

but it does allow:

1 T( "blah % (name)s blah", dict(name= 'Tim'))

The requested language is determined by the "Accept-Language" field in the HTTP header, but this selection can be overwritten programmatically by requesting a specific file, for example:

which reads the "languages/it-it.py" language file. Language files can be created and edited via the administrative interface.

Normally, string translation is evaluated lazily when the view is rendered; hence, the translator force method should not be called inside a view.

It is possible to disable lazy evaluation via

In this way, strings are translated immediately by the T operator based on the currently accepted or forced language.

A common issue is the following. The original application is in English. Suppose that there is a translation file (for example Italian, "it-it.py") and the HTTP client declares that it accepts both English (en) and Italian (it-it) in that order. The following unwanted situation occurs: web2py does not know the default is written in English (en). Therefore, it prefers translating everything into Italian (it-it) because it only found the Italian translation file. If it had not found the "it-it.py" file, it would have used the default language strings (English).

There are two solutions for this problem: create a translation language for English, which would be redundant and unnecessary, or better, tell web2py which languages should use the default language strings (the strings coded into the application). This can be done with:

T. current.languages IS a list of languages that do not require translation.

Notice that 'it' and 'it-it' are different languages from the point of view of web2py. To support both of them, one would need two translation files, always lower case. The same is true for all other languages. The currently accepted language is stored in

1 T.accepted_language

+1 0

Average user rating: 5 stars out of 1 votes

Post a comment

  • Receive news updates via email from this site