Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template: Translate include with variable

I have a template in which you can pass a text variable. I want to include this template into another one but with a translated text as it's variable. How can you achieve this?

I would like something like this:

{% include "a_dir/stuff.html" with text={% trans "Load more promotions" %} %}

I tough about writing my own template tag that will perform a ugettext but then when creating the .po file, the text variable will not be taken automatically.

I don't want to do this work in the view since all our translations take place in the templates.

like image 936
Gab Avatar asked Jul 18 '14 18:07

Gab


People also ask

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does include does in Django template?

The include tag allows you to include content from another template. Place the include tag exactly where you want the content to be displayed. This is useful when you have the same content for many pages.

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 is Forloop counter in Django?

A for loop is used for iterating over a sequence, like looping over items in an array, a list, or a dictionary.


2 Answers

You can put the translated string into a variable with the as syntax. For instance:

{% trans "Load more promotions" as promotions %}
{% include "a_dir/stuff.html" with text=promotions %}

See the docs for more details.

like image 167
Seb D. Avatar answered Sep 22 '22 12:09

Seb D.


A shorter way is

{% include 'a_dir/stuff.html' with text=_("Load more promotions") %}

which also works fine with variables

like image 44
ProfHase85 Avatar answered Sep 18 '22 12:09

ProfHase85