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

时间:2013-10-28 05:47:01

标签: python django

这是我在模板中的代码。

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

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

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

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

2 个答案:

答案 0 :(得分:82)

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

由于您已经在{% if %}标记内,因此无需将request.build_absolute_uri标记为{{...}}

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

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

答案 1 :(得分:2)

可能为时已晚,但这是一个轻量级版本:

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

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