python学习第3天---django框架---模板应用
目录
内容
1、模板创建
- 模板目录:在项目根目录的下创建文件夹,默认名称templates.
- 分级: 一个项目下可能有多个应用,建议给每个应用创建单独的目录,本例创建book目录
- 模板文件:在刚创建的应用目录下创建模板文件,既html文件,本例index.html
- 图示:
2、模板配置
- 说明: 新建了模板目录,路径需要注册到应用中,应用才能识别,配置文件为book/settings
- 图示2-1:
3、模板渲染
- 位置: 既在对应的视图函数中用导入的render函数渲染模板,生成标准的html文档,然后返回客户端
- 示例源码:
from django.shortcuts import render
# Create your views here.
def index(request):
# return HttpResponse('欢迎进入书籍管理系统')
return render(request, 'book/index.html');
- 图示:
- 3-1:
- 3-2:
4、模板文件传输数据
- 普通变量:模板文件中{{ 变量名 }},既输出变量值
- 复杂变量:需要配合控制结构语句,比如判断,循环。
- vuews.py 源码:
from django.shortcuts import render
# Create your views here.
def index(request):
# return HttpResponse('欢迎进入书籍管理系统')
return render(request, 'book/index.html', {'title': '书籍列表', 'books': ['西游记', '红楼梦', '水浒传']});
- index.html源码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.test {
width: 200px;
height: 100px;
margin: 0 auto;
}
li {
color: green;
}
</style>
</head>
<body>
<div class="test">
<h3 style="color: orange">书籍管理首页</h3>
<p>{{ title }}</p>
<ul>
{% for book in books %}
<li>
{{ book }}
</li>
{% endfor %}
</ul>
</div>
</body>
</html>
- 效果图4-1:
后记 :
本项目为参考某音python系列视频。上面为自己参考写的学习笔记,持续更新。欢迎交流,本人QQ:806797785