Skip to main content
 首页 » 编程设计

python之使用 `With` 标签反转 Django 模板中的 bool 值

2025年05月04日31lyj

我想将一个值传递给 include 标记,该标记与传入的变量相反。

这是我尝试过的(基本上):

{% with s_options as not disp %} 
    {% include "e.html" with show_options=s_options only %} 
{% endwith %} 

有什么办法可以做我想做的事吗?

请您参考如下方法:

这有点像使用内置过滤器的 hack yesno ,但它有效:

{% with reversed_value=original_value|yesno:',True' %} 
    {# Do something #} 
{% endwith %} 

请注意 'True' 之前的逗号。它的工作方式是,如果原始值为 True,yesno 将返回一个空字符串,如果您对其进行任何 bool 运算,它将评估为 False。