Search code examples
pythondjangotemplatesif-statementlang

Django: Issues with if condition in templates


I want to print something on the basis of the current language code. For that I did something like this:

{% if request.LANGUAGE_CODE == en %}
    <h1>English</h1>
{% endif %}

But this if condition does not compare the current language code. But if I print this {{request.LANGUAGE_CODE}} on the same page then it will print en as language code, but my if condition is not working and I don't know why ??


Solution

  • LANGUAGE_CODE is a string, so you just need to enquote your comparison value like this:

    {% if request.LANGUAGE_CODE == 'en' %}
        <h1>English</h1>
    {% endif %}
    

    check also the ifequal tag

    {% ifequal request.LANGUAGE_CODE 'en' %}
        ...
    {% endifequal %}
    

    a bit more: the if and ifequal on strings are case sensitive, so you may want to be sure you're matching the correct case (maybe applying the |lower filter to both arguments)