Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: How to force translation into a given language inside a template?

In a Django template, I need to transanlate some strings to a specific language (different from current one).

I would need something like this:

{% tans_to "de" "my string to translate" %}
or
{% blocktrans_to "de" %}my bloc to translate {% endblocktrans_to %}

to force translation to German.

I know I can call the following code in a view:

gettext.translation('django', 'locale', ['de'], fallback=True).ugettext("my string to translate")

Do I need to create a specific template tag ? Or does it already exist a dedicated tag in Django ?

like image 957
Pierre-Jean Coudert Avatar asked Jul 04 '10 21:07

Pierre-Jean Coudert


People also ask

How do I translate text in Django?

Use the function django. utils. translation. gettext_noop() to mark a string as a translation string without translating it.

What does {% %} mean in Django?

{% extends variable %} uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.

How do I change the language on Django?

Create a language switcher template Firstly, add a {% load i18n %} line at the top to load Django i18n-related tags. Open up an HTML form with its action set to send a POST request to set_language view. Note: As mentioned in the Django documentation, this view specifically expects a POST request to be sent.

How does Django discover language preferences?

This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations. Failing that, it uses the global LANGUAGE_CODE setting.


1 Answers

From Django version 1.6, there is a language template tag so you can simply pass the desired language code:

{% language "de" %}my block to translate{% endlanguage %}
like image 66
Harley Holcombe Avatar answered Nov 15 '22 09:11

Harley Holcombe