if/for django

ifequal

Output the contents of the block if the two arguments equal each other.html

Example:python

{% ifequal user.id comment.user_id %}     ...{% endifequal %}

As in the if tag, an {% else %} clause is optional.django

The arguments can be hard-coded strings, so the following is valid:oop

{% ifequal user.username "adrian" %}     ...{% endifequal %}

It is only possible to compare an argument to template variables or strings. You cannot check for equality with Python objects such as True or False. If you need to test if something is true or false, use the if tag instead.ui


Boolean operators

if tags may use and, or or not to test a number of variables or to negate a given variable:this

{% if athlete_list and coach_list %}     Both athletes and coaches are available.{% endif %} {% if not athlete_list %}     There are no athletes.{% endif %} {% if athlete_list or coach_list %}     There are some athletes or some coaches.{% endif %} {% if not athlete_list or coach_list %}     There are no athletes or there are some coaches (OK, so
    writing English translations of boolean logic sounds
    stupid; it's not our fault).{% endif %} {% if athlete_list and not coach_list %}     There are some athletes and absolutely no coaches.{% endif %}
Changed in Django 1.2:  Please see the release notes

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.g.:spa

{% if athlete_list and coach_list or cheerleader_list %}

will be interpreted like:code

if (athlete_list and coach_list) or cheerleader_list

Use of actual brackets in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.htm



for ... empty

The for tag can take an optional {% empty %} clause that will be displayed if the given array is empty or could not be found:索引

<ul> {% for athlete in athlete_list %}     <li>{{ athlete.name }}</li> {% empty %}     <li>Sorry, no athlete in this list!</li> {% endfor %} <ul>

The above is equivalent to -- but shorter, cleaner, and possibly faster than -- the following:

<ul>   {% if athlete_list %}     {% for athlete in athlete_list %}       <li>{{ athlete.name }}</li>     {% endfor %}   {% else %}     <li>Sorry, no athletes in this list.</li>   {% endif %} </ul>

 

 

表F-1. {% for %}循環中的可用變量

變量名 描述
forloop.counter 當前循環次數(索引最小爲1)。
forloop.counter0 當前循環次數 (索引最小爲0)。
forloop.revcounter 剩餘循環次數 (索引最小爲1)。
forloop.revcounter0 剩餘循環次數 (索引最小爲0)。
forloop.first 第一次循環時爲 True 。
forloop.last 最後一次循環時爲 True 。
forloop.parentloop 用於嵌套循環,表示當前循環外層的循環
相關文章
相關標籤/搜索