Reputation: 437
I have the following in my html file:
{% trans "Result: "%} {{result}}
Which will print out the word SUCCESS on the browser (because thats what the string contains)
But If I do the following:
{% if result == 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
I find that the if statement does not work as expected.
Why is this??
Upvotes: 2
Views: 1401
Reputation: 1287
Check this link: Django String format. according to django documentation you should use this format:
{% if result|stringformat:"s" == 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
or
{% if result|stringformat:"s" in 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
or
{% ifequal result|stringformat:"s" 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
this problem happen because of your variable type, you should change it to string before compare it to another string.
Upvotes: 1
Reputation: 11686
The if
statement works fine. Your problem must be regarding the string. Maybe it's not a string at all.
Try the ifequal
templatetag:
{% ifequal result 'SUCCESS' %}
do something
{% else %}
do something else
{% endifequal %}
You can try different things. If you're assigning result
in a view, you can validate it's a string in that very same view:
def my_view(request):
# ... processing ...
result = something()
# Let's make sure it's a string containing 'SUCCESS'
assert type(result) == str
assert result == 'SUCCESS'
You can apply the same logic if it's a context processor. https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#ifequal
Upvotes: 3