1.深度变量查找: "." 点号
2.变量的过滤器filter
语法格式: {{obj|filter:para}} 冒号前后不能有空格、
filter函数:
add:给obj增加数值
capfirst:首字母大写
cut:移除字串中的指定字符
date:格式化日期字符串
default:如果值是False,就提换成设置的默认值,否则就用原本的值,将传过来的空字符串显示为字串,可以起到提示的作用
default_if_none: 如果值是None,就替换成设置的默认值,否则就用本来的值
safe:告诉浏览器这是安全的,对a标签可以渲染,不加safe,标签a就是源码显示
另外一个安全机制:
{% autoescape off %}
<h1>{{ a }}</h1>
{% endautoescape %}
3.标签(tag)的使用:使用大括号和百分比的组合来表示
#views.py
def query(request):
l=["团长","连长","局长"]
d={"name": "Tom","age":48,"hobby": "sleep"}
c=Animal("lihua","female")
test="hello world"
test2="h ell o wo rld"
num=10
t=datetime.datetime.now()
e=[]
a="<a href=''>click</a>"
return render(request,"index.html",locals())
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>hello {{ action.0 }}</h1>
<h1>hello {{ d.name }}</h1>
<h1>hello {{ d.age }}</h1>
<h1>hello {{ c.name }}</h1>
<h1>hello {{ c.sex }}</h1>
<h1>tom的真实年纪:{{ d.age|add:12 }}</h1>
<h1>{{ test|capfirst }}</h1>
<h1>{{ test2|cut:" " }}</h1>
<h1>{{ t|date:"Y-m-d" }}</h1>
<h1>{{ e|default:"空的列表" }}</h1>
<h1>{{ a|safe }}</h1>
{% autoescape off %}
<h1>{{ a }}</h1>
{% endautoescape %}
{% if d.age > 20 %}
{% if d.age < 50 %}
<h1>{{ d.name }}的年纪大于20小于50</h1>
{% else %}
<h1>hello {{ d.name }}</h1>
{% endif %}
{% elif d.age > 10 %}
<h1>{{ d.name }}的年龄大于10岁小于20</h1>
{% else %}
<h1>{{ d.name }}的年纪小于10岁</h1>
{% endif %}
{#forloop.counter表示循环的次数,默认从1开始计数,要想从0开始计数forloop.counter0#}
{% for name in l %}
{{ name }}
<h1>{{ forloop.counter0 }}:{{ name }}</h1>
<h1>{{ forloop.revcounter0 }}:{{ name }}</h1>
{% endfor %}
</body>
</html>
访问:
在terminal中启动项目: python manage.py runserver 8083
在本地浏览器中访问: http://127.0.0.1:8083/query
浏览器访问结果:
hello
hello Tom
hello 48
hello lihua
hello female
tom的真实年纪:60
Hello world
helloworld
2019-07-04
空的列表
click
click
Tom的年纪大于20小于50
团长
0:团长
连长
1:连长
局长