django 'if' statement improperly formatted

吃可爱长大的小学妹 提交于 2019-12-04 18:59:54
Mark Stahler

Until Django 1.2 lands you are looking for "Smart If", a Django Template Tag.

A smarter {% if %} tag for django templates.

While retaining current Django functionality, it also handles equality, greater than and less than operators. Some common case examples::

    {% if articles|length >= 5 %}...{% endif %}
    {% if "ifnotequal tag" != "beautiful" %}...{% endif %}

Arguments and operators must have a space between them, so {% if 1>2 %} is not a valid smart if tag.

All supported operators are: or, and, in, = (or ==), !=, >, >=, < and <=.

As mentioned, you can't use operators in the {% if %} tag. It accepts only Boolean values (which you can AND, OR and NOT together.)

For simple equality, you can use the {% ifequal val1 val2 %} tag.

The reason is to push the "logic" out of the template and into the model layer. I.e. you should have a method on your model like so:

def positive_diff(self):
   return self.diff >= 0

Then call that in your template:

{% if x.positive_diff %} ... {% endif %}

Or, you can set an extra variable in your view:

positive_diff = diff >= 0

You need to close each if statement with an endif

{% if var1 %}

{{ var1|safe }} 

{% else %}

{% if var2 %}

{{ var2|safe }}

{% else %}

{% if var3 %}

{{ var3|safe }}

{% endif %}{% endif %}{% endif %}

The "smart if" tag was just added in the development version (that will eventually become 1.2).

If you're using a stable release (1.1.x or earlier) you won't be able to use those comparison operators in the "if" template tag.

Edit: look just above the == operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!