3Django视图层和模板层
原创
©著作权归作者所有:来自51CTO博客作者wx5d4124a358e8a的原创作品,请联系作者获取转载授权,否则将追究法律责任
1视图层与模板层之间的交互y以及模板过滤器的使用:
过滤器
| 说明
|
lower
| 将字符串转换成小写
|
upper
| 将字符串转换成大写
|
safe
| 默认不对变量内的字符串进行html转义
|
add:"n"
| 将value值增加n
|
truncatechars:'n'
| 如果字符串字符多于指定的字符数量,那么会被截断。阶段的字符串以省略号为结尾
|
VIEWS:
#方法
def say_hi():
return 'ha ha ha'
#类的实例化对象
class Dog:
def say(self):
return 'wang wang'
def test_html_parm(request):
dic = {}
dic['int'] = 88
dic['str'] = 'zhangsan'
dic['lst'] = ['tom','jack','lily']
dic['dict'] = {'a':9,'b':8}
dic['func'] = say_hi
dic['class'] = Dog()
dic['script'] = '<script>alert(1111)</script>'
return render(request,'test_html_param.html',dic)
Templates:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h3>int是{{ int|add:"2" }}</h3> <!--用过滤器给传过来的值加2-->
<h3>str是{{ str|upper }}</h3> <!--把传过来的字符串转换成大写-->
<h3>lst是{{ lst }}</h3>
<h3>lst是{{ lst.0 }}</h3>
<h3>dict是{{ dict }}</h3>
<h3>dict['a']是{{ dict.a }}</h3>
<h3>function是{{ func }}</h3>
<h3>class_obj是{{ class_obj.say }}</h3>
<h3>script是{{ script|safe }}</h3> <!--不转义-->
</body>
</html>
2模板标签{%%}:
将python的一些功能嵌入到模板中,例如if判断,循环遍历等,但需要注意的是if标签中使用括号可能会无效
for标签内置变量forloop:
forloop.counter
| 循环的当前迭代(从1开始索引)
|
forloop.counter0
| 循环的当前迭代(从0开始索引)
|
forloop.revcounter
| counter值的倒序。从后往前开始索引,与counter相反
|
forloop.recounter0
| recounter值的倒序,从0开始算倒着来,与counter0相反
|
forloop.first
| 如果这是第一次通过循环,则为真
|
forloop.last
| 如果这是最后一次循环,则为真
|
forloop.parentloop
| 嵌套循环中,parentloop表示外层循环
|
小练习:
视图:
def test_if_for(request):
dic = {}
dic['lst'] = ['tom','jack','lucy']
return render(request,'test_if_for.html',dic)
路由:
'test_if_for',views.test_if_for),
模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for name in lst %}
{% if forloop.first %} ----开头----- {% endif %}
{{ forloop.counter }}{{ name }}
{% if forloop.last %}-----结尾------{% endif %}
{% empty %}
当前没数据
{% endfor %}
</body>
</html>
3模板的继承
子模板可以继承父模板,子模板可重写父模板中定义的block块,子模板无法继承父模板中动态变量获取到的内容,子模板继承父模板的方法是在第一行引入父模板,例如:{% extends 'base.html'%}
练习:
VIEWS:
def base_view(request):
lst = ['tom','jack']
return render(request,'base.html',locals())
def music_view(request):
return render(request,'music.html')
def soport_view(request):
return render(request,'sport.html')
URL:
'base_index',views.base_view),
path('sport_index',views.soport_view),
path('music_index',views.music_view),
]
Template:
base父模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{% block mytitle %}
<title>标题可修改</title>
{% endblock %}
</head>
<body>
<a href="">这是网站头部不可修改</a>
{{ lst }}
<a href="/music_index"> 音乐频道</a>
<a href="/sport_index">体育频道</a>
<br>
{% block info %}
这是主页身体部分,可修改
{% endblock %}
<h3>这是网站尾部不可修改</h3>
</body>
</html>
子模版1:sport.html
{% extends 'base.html' %}
{% block mytitle %}
<title>体育频道</title>
{% endblock %}
{% block info %}
欢迎来到体育频道
{% endblock %}
子模版2:music.html
{% extends 'base.html' %}
{% block mytitle %}
<title>音乐频道</title>
{% endblock %}
{% block info %}
欢迎来到音乐频道
{% endblock %}