Django 无效的块标签:endelse 和 ifequal

2 投票
3 回答
2269 浏览
提问于 2025-04-18 11:32

我想用 Django 的 ifequalelse 标签来判断一个变量是否等于 8022。所以,我写了这段代码:

{% if firewalls %}
<thead>
  <tr>
    <th>IP address</th>
    <th>Function</th>
  </tr>
</thead>
{% endif %}
<tbody>
{% for firewall in firewalls %}
  <tr>
    <td>{{ host_ip }} : {{ firewall.from_port }}</td>

    {% ifequal firewall.to_port 22 %} <td>Ssh Service</td>
    {% ifequal firewall.to_port 80 %} <td>Web Service</td>
    {% else %} <td>Unknown Service</td>{% endifequal %}{% endelse %}

  </tr>
{% endfor %}

但是出现了一个错误,提示 Invalid block tag: 'endelse', expected 'else' or 'endifequal'。有人能帮我吗?非常感谢!

3 个回答

0
    {% ifequal firewall.to_port 22 %} <td>Ssh Service</td>{% endifequal %}
    {% ifequal firewall.to_port 80 %} <td>Web Service</td>{% endifequal %}
    {% if firewall.to_port !=22 and if firewall.to_port !=80   %} <td>Unknown Service</td>{% endif %}

每次使用 ifequal 时,都需要用 endifequal 来结束它。你漏掉了一个。

2

Django支持等于运算符。为了帮你解决代码问题,我会使用:

{% if firewalls %}
<thead>
  <tr>
    <th>IP address</th>
    <th>Function</th>
  </tr>
</thead>
{% endif %}
<tbody>
{% for firewall in firewalls %}
  <tr>
    <td>{{ host_ip }} : {{ firewall.from_port }}</td>

    {% if firewall.to_port==22 %} <td>Ssh Service</td>
    {% elif firewall.to_port==80 %} <td>Web Service</td>
    {% else %} <td>Unknown Service</td>{% endif %}

  </tr>
{% endfor %}
6

一个替代 ifequal 标签的方法是使用 if 标签和 == 运算符。让我们来看看 '==' 运算符的强大之处:

{% if firewall.to_port == 20 %}
   <td>Ssh Service</td>
{% elif firewall.to_port == 80 %}
   <td>Web Service</td>
{% else %}
   <td>Unknown Service</td>
{% endif %}

这样做还可以节省代码处理时间,因为它不会对每个端口号都评估所有的 if 条件。

撰写回答