Django(六): 模板基础

模板:  Template + Context
1. 基本流程:
from django.template import Template, Context
from django.template.load import get_template
1>. 具体过程
# t = Template('<h1>My name is {{name}}</h1>')
t = get_template('name.html')
c = Context({'name':'xzq})
html = t.render(c)
return HTTPResponse(html)
2>. 简写:
return render(req, 'name.html', {'name':'xzq'})

2. Template支持的变量类型:
1>. Template中的变量定义: {{ variable }}
2>. 支持的类型: 基本变量类型(num, str, boolean)
类对象或对象类型(list, dict, obj)
3>. 深度变量查找: .attr .func (不能传参)

3. Template过滤器:
1>. Template中定义过滤器: {{obj|filter[:param]}}
2>. filter类型: add: num # 给变量加上相应的值
cut: 'str' # 移除变量中的指定字符, 会移除所有(pythonstrip不同)
date: 'Y-m-d-H-M-S' # 指定日期格式 %Y %m %d %X时间(%H %M %S) %a星期
default: 0 # 变量为False, 指定默认值
default_if_none: 0 # 变量为None, 指定默认值
safe # 申明变量为安全, 可以翻译成html

4. Template控制语句:
1>. 语法: {% tag %}
2>. if语句:
{% if condition1 %}
# pass
{% elif condition2 %}
# pass
{% else %}
{% endif %}
# 支持 and or not
3>. for语句:
{% for item in list,dict %}
# pass
{% endfor %}
* 不支持break continue
* forloop提供循环信息: forloop.counter # 循环计数 1 开始
forloop.counter0 # 循环计数 0 开始
forloop.first # 第一次循环为true

5. 其他:
1>. url语句:
{% url 'reg' %} # 引用路由配置

2>. 表单验证:
{% csrf_token %} # 会在wsgi服务器中渲染成input标签, 其值为提交的钥匙. 表单在提交时服务器会先验证该钥匙,正确则让提交。
# 防止跨站攻击验证
3>. 变量重命名:
{% with local_name = input_name %}
{{ local_name }}
{% endwith %}

4>. 禁止wsgi服务器渲染:
{% verbatim %}
{{ hello }}
{% endverbatim %}

5>. 加载标签库: {% load %}

猜你喜欢

转载自www.cnblogs.com/lancelotxly/p/10871580.html