python学习第3天---django框架---模板应用

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

  1. 原视频地址:https://space.bilibili.com/277754748?spm_id_from=333.788.b_765f7570696e666f.1
  2. 笔记项目源代码地址:https://gitee.com/gaogzhen/python
发布了22 篇原创文章 · 获赞 6 · 访问量 6769

猜你喜欢

转载自blog.csdn.net/gaogzhen/article/details/105389130