Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Django translated variable (trans) in template if statement

I am facing a prob in django. The following is my code snippet :

{% if pageName != 'My page Name' %}
  .....{{ then this }}

Now this works fine for English , Now when i translated my application in another language the pageName also changed according to that language. So the above logic is not working as it is hard coded English

So i have to try to implement the logic with translated version of 'My page Name'. But i cant use it directly in if like :

{% if pageName != trans 'My page Name' %} 

So I thought of storing the translated version in another variable and then check with that variable like :

{%blocktrans%} "My page Name" {{myvar}} {%endblocktrans%}
{% if pageName != myvar %}

But this is also not working myvartakes the value "My page Name" , not the translated version of it.

Any clue how to fix it. Thanks in advance.

like image 878
curiousguy Avatar asked Feb 27 '14 07:02

curiousguy


People also ask

How to translate a string in Django templates?

In Django templates, you can use either { { _ ("Hello World") }} or {% trans "Hello World" %} to mark strings to be translated. In docs, the “official” approach seems to be the {% trans %} tag, but the _ () syntax is mentioned too once. How these approaches differ (except syntax) and why should be one preferable rather than the other?

What is the IF template tag in Django?

The if template tag is one of the template tags in Django that can be used to render HTML content for a particular condition. Let us see how to use the if template tag in Django.

How to render if condition in a Django template?

The syntax of the if template tag is: In a Django template, you have to close the if template tag. You can write the condition in an if template tag. Inside the block, you can write the statements or the HTML code that you want to render if the condition returns a True value.

Does variable translation work in templates?

My experience here is that variable translation does not work in templates on its own. However I came to a suitable solution when the content of the variables is known (I mean that they are not free text, but a set of choices you set in the database). You need to force the translation in the view or in a filter tag.


1 Answers

You can use trans template tag but this way

{% trans "My page Name" as myvar %} 
{% if pageName != myvar %}
...

See trans template tag

like image 122
fragles Avatar answered Nov 08 '22 09:11

fragles