如何在 Django 模板中查看一个字符串是否包含另一个字符串

这是我在模板中的代码。

{% if 'index.html' in  "{{ request.build_absolute_uri  }}" %}
'hello'
{% else %}
'bye'
{% endif %}

现在我的 url 值当前是 "http://127.0.0.1:8000/login?next=/index.html"

即使字符串中有 "index.html",它仍然打印再见。

当我在 pythonshell 中运行相同的代码时,它能正常工作。

128135 次浏览

Try removing the extra \{\{...}} tags and the "..." quotes around request.build_absolute_uri, it worked for me.

Since you are already within an {% if %} tag, there is no need to surround request.build_absolute_uri with \{\{...}} tags.

{% if 'index.html' in request.build_absolute_uri %}
hello
{% else %}
bye
{% endif %}

Because of the quotes you are literally searching the string "\{\{ request.build_absolute_uri }}" and not the evaluated Django tag you intended.

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'
>>>

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' }}