Django 内建模板
Django内建的模板非常丰富,下面几个是我们会经常用到的,但是与其它的模板有一些差异,尤其是我们需要比较两个变量的值是否相等,我们最先想到的可能是用==,但是在django模板中好像不太好用,因此查阅了一些官方的Doc发现了ifequal这个东东可以用,下面摘录了一些官方Doc内容方便以后参考。
ifchanged
Check if a value has changed from the last iteration of a loop.
The {% ifchanged %} block tag is used within a loop. It has two possible uses.
-
Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:
<h1>Archive for {{ year }}</h1> {% for date in days %} {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> {% endfor %}
-
If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed:
{% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %}
The ifchanged tag can also take an optional {% else %} clause that will be displayed if the value has not changed:
{% for match in matches %}
<div style="background-color:
{% ifchanged match.ballot_id %}
{% cycle "red" "blue" %}
{% else %}
grey
{% endifchanged %}
">{{ match }}</div>
{% endfor %}
ifequal
Output the contents of the block if the two arguments equal each other.
Example:
{% ifequal user.id comment.user_id %}
...
{% endifequal %}
As in the if tag, an {% else %} clause is optional.
The arguments can be hard-coded strings, so the following is valid:
{% 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.