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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19627911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 14:13:35  来源:igfitidea点击:

How to See if a String Contains Another String in Django Template

pythondjango

提问by curiousguy

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"

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

Even though "index.html"is there in the string it still prints bye.

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

When I run the same code in a python shell it works. Not sure what the mistake is.

当我在 python shell 中运行相同的代码时,它可以工作。不知道是什么错误。

采纳答案by Farmer Joe

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

尝试删除额外的{{...}}标签和"..."周围的引号request.build_absolute_uri,它对我有用。

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

由于您已经在{% if %}标签中,因此无需request.build_absolute_uri{{...}}标签包围。

{% 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.

由于引号,您实际上是在搜索字符串,"{{ request.build_absolute_uri }}"而不是您想要的评估的 Django 标签。

回答by chenchuk

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:

这可以用 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'
>>>