Django模板


{% load static %}

Django 注释使用 {# #}。

{# 这是一个注释 #}




{% for m in music_name_list %}

{{ m }}


{% endfor %}

{% for i,j in views_dict.items %}

{{ i }}---{{ j }}

{% endfor %}

if/else 标签

基本语法格式如下:

{% if condition %}
     ... display
{% endif %}

或者:

{% if condition1 %}
   ... display 1
{% elif condition2 %}
   ... display 2
{% else %}
   ... display 3
{% endif %}

在 {% for %} 标签里可以通过 {{forloop}} 变量获取循环序号。
  • forloop.counter: 顺序获取循环序号,从 1 开始计算
  • forloop.counter0: 顺序获取循环序号,从 0 开始计算
  • forloop.revcounter: 倒序获取循环序号,结尾序号为 1
  • forloop.revcounter0: 倒序获取循环序号,结尾序号为 0
  • forloop.first(一般配合if标签使用): 第一条数据返回 True,其他数据返回 False
  • forloop.last(一般配合if标签使用): 最后一条数据返回 True,其他数据返回 False

可选的 {% empty %} 从句:在循环为空的时候执行(即 in 后面的参数布尔值为 False )。

即遍历对象为空时执行。

{% for i in listvar %}

{{ forloop.counter0 }}

{% empty %}

空空如也~

{% endfor %}

ifequal/ifnotequal 标签

{% ifequal %} 标签比较两个值,当他们相等时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。

{% ifequal user currentuser %}
    

Welcome!h1> {% endifequal %}

和 {% if %} 类似, {% ifequal %} 支持可选的 {% else%} 标签:8

{% ifequal section 'sitenews' %}
    

Site Newsh1> {% else %}

No News Hereh1> {% endifequal %}

{% include %} 标签允许在模板中包含其它的模板的内容。

下面这个例子都包含了 nav.html 模板:

{% include "nav.html" %}
 

csrf_token

csrf_token 用于form表单中,作用是跨站请求伪造保护。

如果不用 {% csrf_token %} 标签,在用 form 表单时,要再次跳转页面会报 403 权限错误。

用了{% csrf_token %} 标签,在 form 表单提交数据时,才会成功。