簡體   English   中英

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

[英]How to See if a String Contains Another String in Django Template

這是我在模板中的代碼。

{% 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" ,它仍然會打印再見。

當我在 python shell 中運行相同的代碼時,它可以工作。 不知道是什么錯誤。

嘗試刪除額外的{{...}}標記和request.build_absolute_uri周圍的"..."引號,它對我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標記。

也許為時已晚,但這是一個輕量級版本:

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

我正在添加“不包含”的否定選項:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM