Python Django`ifnotequal`tag
我想使用Python Django`ifnotequal`tag,python,django,Python,Django,我想使用ifnotequal标记来判断变量是否等于某个值。代码如下: {% ifequal firewall.to_port 22 %} <td>Ssh Service</td>{% endifequal %} {% ifequal firewall.to_port 80 %} <td>Web Service</td>{% endifequal %} {% ifequal firewall.to_port 25 %} <td>Mail
ifnotequal
标记来判断变量是否等于某个值。代码如下:
{% ifequal firewall.to_port 22 %} <td>Ssh Service</td>{% endifequal %}
{% ifequal firewall.to_port 80 %} <td>Web Service</td>{% endifequal %}
{% ifequal firewall.to_port 25 %} <td>Mail Service</td>{% endifequal %}
{% ifnotequal firewall.to_port 80 or 22 or 25 %} <td>Unknown Service</td>{% endifnotequal %}
这似乎很愚蠢。一种方法是使用
if
模板标记,而不是ifequal
。它可以有多个elif
子句,如果没有使用elif
子句,则将使用一个最终的else
子句。例如:
{% if firewall.to_port==22 %} <td>Ssh Service</td>
{% elif firewall.to_port==80 %} <td>Web Service</td>
{% elif firewall.to_port==25 %} <td>Mail Service</td>
{% else %} <td>Unknown Service</td>{% endif %}
{%if firewall.to_port==22%}Ssh服务
{%elif firewall.to_port==80%}Web服务
{%elif防火墙。到_端口==25%}邮件服务
{%else%}未知服务{%endif%}
根据to_port
调用的工作方式,您可能需要比较字符串而不是整数
在查看上面评论中的重复链接Henrik Andersson后,我发现有人已经在那里提出了这种方法。这不是唯一的选项,但如果您不想更改视图/模型实例的行为,它会起作用。在将对象发送到模板之前,在视图中执行此操作更容易,性能也更好:
def some_view(request):
port_names = {22: 'SSH Service', 80: 'Web Service', 25: 'SMTP Service'}
firewall_objects = Firewall.objects.all()
object_list = []
for firewall in firewall_objects:
object_list.append((firewall,
port_names.get(firewall.to_port, 'Unknown Service')))
return render(request, 'template.html', {'object_list': object_list})
现在,在您的模板中,您的生活很轻松:
<ul>
{% for obj, description in object_list %}
<li>{{ obj.to_port }} - {{ description }}</li>
{% endfor %}
</ul>
{对象的%s,对象列表中的描述%}
- {{obj.to_port}}-{{description}}
{%endfor%}
再次发布..以前的工作是否可能重复
<ul>
{% for obj, description in object_list %}
<li>{{ obj.to_port }} - {{ description }}</li>
{% endfor %}
</ul>