'How to See if a String Contains Another String in Django Template
This is my code in a template.
{% if 'index.html' in "{{ request.build_absolute_uri }}" %}
'hello'
{% else %}
'bye'
{% endif %}
Now my url value currently is "http://127.0.0.1:8000/login?next=/index.html"
Even though "index.html" is there in the string it still prints bye.
When I run the same code in a python shell it works. Not sure what the mistake is.
Solution 1:[1]
Maybe too late but here is a lightweight version :
{{ 'hello 'if 'index.html' in request.build_absolute_uri else 'bye' }}
This can be tested with Jinja:
>>> from jinja2 import Template
>>> t = Template("{{ 'hello 'if 'index.html' in request.build_absolute_uri else 'bye' }}")
>>> request = {}
>>> request['build_absolute_uri']='...index.html...'
>>> t.render(request=request)
'hello '
>>> request['build_absolute_uri']='something else...'
>>> t.render(request=request)
'bye'
>>>
Solution 2:[2]
I am adding the negative option of "not contains":
{% if 'index.html' not in request.build_absolute_uri %}
hello
{% else %}
bye
{% endif %}
And:
{{ 'hello 'if 'index.html' not in request.build_absolute_uri else 'bye' }}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Yakir GIladi Edry |
