letoosh
letoosh

Reputation: 531

Django translation: pick variables

We're building a project, where we need to translate notifications into different languages.

The problem is that, unlike standard "Hello, %(first_name)s", we need to have "Halo, Herr %(last_name)s" depending on the language.

Another words, the variables we want to use in the translated block depend on the language.

What would be the best way to implement it? I would really like to avoid having to implement different templates for every language..

Thanks!

Upvotes: 1

Views: 290

Answers (1)

Udi
Udi

Reputation: 30472

Having:

user_data = {
    'first_name': 'Charlie', 
    'last_name': 'Brown',
}

1.

Compiling _('Hello, %(first_name)s') % user_data, while supplying the translation Halo, Herr %(last_name)s results in a a format specification for argument 'first_name' doesn't exist in 'msgstr' error, however the mo file is created, and the translation works ok! (Tested with gettext 0.18.1 running under windows).

2.

You can use python newer string formatting: _('Hello, {first_name}').format(**user_data), and translate into Halo, Her, {last_name}

3. Hackish:

_("Hello %s") % (user_data[_('hello_name_field')])

#or uglier but safe:
_("Hello %s") % (user_data.get(_('hello_name_field'), user_data['first_name'])

Upvotes: 1

Related Questions