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 myvar
takes the value "My page Name"
, not the translated version of it.
Any clue how to fix it. Thanks in advance.
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?
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.
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.
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.
You can use trans template tag but this way
{% trans "My page Name" as myvar %}
{% if pageName != myvar %}
...
See trans template tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With