常用的模板标签
if标签。需要{% %}包裹。可以使用==, !=, <, <=, >, >=, in, not in, is, is not等判断运算符- 变量名直接写,不用
{{}}包裹,包裹的是要输出的
- 变量名直接写,不用
for...in...标签。可以遍历列表,元组,字符串,字典等- 添加
reversed可以翻转顺序 - 在
DTL中,执行一个方法不能使用圆括号的形式。遍历字典的时候,如果需要itemskeysvalues方法,用dict.items这种方式获得 for循环中,DTL提供了一些变量可供使用forloop.counter: 当前循环的下标。以1作为起始值forloop.counter0: 当前循环的下标。以0作为起始值forloop.revcounter: 当前循环的方向下标值。默认1是最后的结束值forloop.revcounter0: 当前循环的方向下标值。默认0是最后你结束值forloop.first: 是否是第一次遍历forloop.last: 是否是最后一次遍历forloop.parentloop: 如果有多次循环嵌套,这个属性代表的是上一级的for循环
for...in...没有continue和break!!!!!!!!!!!!!
- 添加
for...in...empty标签。 如果遍历的对象没有元素,会执行empty中的内容if和for标签
视图代码 ```python def func(request): d = { “number”: 100, “lists”: [
1,2,"a",
], “dicts”: {
"index1": 111,"index2": 222,"index3": 333,
}, “empty_dicts”: {
},
} return render(request, “index.html”,context=d) ```
- 前端代码
```html
<!DOCTYPE html>
{% if number > 50 %} 大于50 {% endif %}
{% for list in lists %}
{{ list }}
{% endfor %}
{% for list in lists reversed %}{{ list }}
{% endfor %}
</h1><h2>{% for dict in dicts %}{{ dict }}{% endfor %}<br>{% for value in dicts.values %}当前的下标是 {{ forloop.counter }}{{ value }}<br>{% endfor %}<br></h2><h3>{% for empty_dict in empty_dicts %}{{ empty_dict }}{% empty %}nothing there{% endfor %}</h3>
- 运行 <br />4. `with`标签。定义变量。有两种使用方式- 视图代码```python# views.pyd = {"person": ["jack","lee",],}def func(request):return render(request, "index.html", context=d)
前端代码one
<!-- html -->{% with name=person.0 %}{{ name }}{% endwith %}
前端代码two
<!-- html -->{% with person.0 as name %}{{ name }}{% endwith %}
注意
=前后不能有空格- 这个别名的作用域只在
with语句块内<!-- html -->{% with person.0 as name %}{{ name }}{{ name }}{% endwith %}{{ name }} {# 这一句没执行 #}
url标签。 类似reverse()函数。会用到映射时URL指定过的名字进行反转<!-- html --><a href="{% url 'book:list' %}"> 列表 </a>(# 这里'book:list'是定义在app_name是book的名为list的URL#){# url和'book:list'之间需要空格,也就是说空格是分隔符#}
views.py
def book_detail(request, book_id): next = request.GET.get(“page”) if next: return HttpResponse(“book_id is {}, query_string is {}”.format(book_id, next))
```html<!-- html -->{# url反转,使用位置参数 #}<a href="{% url 'book:detail’ 1 %}"> 页面 </a> {# 位置参数根据URL的变量位置进行排列 #}{# url反转, 使用关键字参数 #}<a href="(% url 'book:detail' book_id=1 %)"> 页面 </a>
如果想要传递查询字符串的参数,必须手动在后面添加
<!-- html --><a href = "{% url 'book:detal' book_id=1 %}?page=1"> 页面 </a>
如果要传递多个参数,那么通过空格进行分割
<!-- html --><a href = {% url 'book:detail' book_id=1 page=2 %}> 页面 </a>
spaceless标签。移除html标签中的空白字符。包括空格、tab键,换行等。使用
{% spaceless %}<p><a href="index/">INDEX</a></p>{% endspaceless %}
渲染完毕后是以下格式
<p><a href="index/">INDEX</a></p>
spaceless只会移除html标签之间的空白字符。而不会移除标签与文本之间的空白字符。
autoescape标签。自动转义,会将哪些特殊字符进行转义,比如会将<转义成<等。DTL默认开启。不容易出现XSS漏洞。def url_page(request):d = dict{"baidu": "<a href = 'http://www.baidu.com'>百度</a>"}
{% autoescape off %}{{ baidu }}{% endautoescape %}
verbatim标签。默认在DTL模板中会去解析哪些特殊字符, 比如{%}和%},{{和}}等。如果在某个代码片段中不想使用这个解析引擎,比如使用了其他类似的模板时,可以把这个代码片段放在verbatim标签中。{% verbatim %}{{ name }}{% endverbatim %}}
