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

cur*_*guy 51 python django

这是我在模板中的代码.

{% if 'index.html' in  "{{ request.build_absolute_uri  }}" %} 
    'hello'
{% else %}      
    'bye'
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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

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

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

Far*_*Joe 90

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

由于您已经在{% if %}标签内,因此无需request.build_absolute_uri使用{{...}}标签.

{% if 'index.html' in request.build_absolute_uri %}
    hello
{% else %}
    bye
{% endif %}
Run Code Online (Sandbox Code Playgroud)

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

  • 完美@farmerjoe` {%if'index.html'在request.build_absolute_uri%}`这对我有用.我应该写自定义模板标签.但这对我有用. (2认同)

che*_*huk 9

也许为时已晚,但这里有一个轻量级版本:

{{ 'hello 'if 'index.html' in request.build_absolute_uri else 'bye' }}
Run Code Online (Sandbox Code Playgroud)

这可以用 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'
>>> 
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢你直接用 Python 测试 Jinja2 模板的技术。我绝对计划在将来使用它。 (4认同)