Django 中模板的 if 条件这样为什么出错了?

2014 年 10 月 30 日
 cheyo
{% if 1==house.status %}
<span class="label label-success">
{% elif 2==house.status %}
<span class="label label-primary">
{% elif 3==house.status %}
<span class="label label-info">
{% elif 4==house.status %}
<span class="label label-default">
{% else %}
<span class="label label-danger">
{% endif %}
{{ house.get_status_display }}</span>

错误信息:
TemplateSyntaxError at /project/19607/
Could not parse the remainder: '==house.status' from '1==house.status'

谢谢
4508 次点击
所在节点    Python
10 条回复
stillwater
2014 年 10 月 30 日
用ifequal?
virusdefender
2014 年 10 月 30 日
{% ifequal a "111" %}{% endifequal %}判断相等
ericls
2014 年 10 月 30 日
if house.status == 1应该可以
注意必须有空格
cheyo
2014 年 10 月 30 日
@ericls 果然加一个空格就行了
@stillwater
@virusdefender 用ifequal也行

谢谢
rcmerci
2014 年 10 月 30 日
模板里空格挺严格的
mornlight
2014 年 10 月 30 日
要有空格,如果你用Pycharm的话应该会提示你
taobeier
2014 年 10 月 31 日
不太习惯的话, 就用个IDE会稍微好点。
tuteng
2014 年 10 月 31 日
mark
gevin
2014 年 10 月 31 日
如果house.status的类型是str,你的代码那个就成了:
{% if 1=='1' %}

这种情况下就会报错

需要保持 '==' 两边值得类型一致
nooper
2014 年 10 月 31 日
Try to remove the complex in the if cases.Just judge by integer , what if the status change , that's should not be hard code in the template. and you'd better add the logic into the views. or templatetags.

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/142716

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX