Django 模板中的 'if and

16 投票
4 回答
48198 浏览
提问于 2025-04-17 16:21

我想在我的Django网页中做以下事情:

{% if myList|length and ifequal myValue 'somestring' %}
blah blah
{% endif %}

但是我遇到了一个错误:

在if表达式的末尾未使用'myValue'

我该如何在模板中使用“如果并且”的逻辑呢?

4 个回答

2

Django文档关于布尔运算符的介绍

应该像这样

  1. view.py
def posts_request(request):  
    message=ApplyPost.objects.filter( blah blah)
    if message:
       return render (request,'blah.html',{'message':message})
  1. blah.html
{% if message %}
     {% for post in message %}
          {% if post.provider %}
              ....
          {% endif %}
          {% if post.accept == True and post.provider %}
              ...
              ...
          {% endif %}
          ....You can add multiple if,elif, with Operators ....
    {% endfor %}
{% if message %}

以及

{% if a == b or c == d and e %}

要注意的是,"and"的优先级比"or"高,而且不能使用括号。如果需要,可以使用嵌套块。

18

应该是像这样的:

{% if myList|length and myValue == 'somestring' %}
   blah blah
{% endif %}
39

试试这个:

{% if myList|length and myValue == 'somestring' %}
    blah blah
{% endif %}

可以参考Django的文档,了解如何在Django模板中使用布尔运算符复杂表达式

撰写回答