经过前面的学习,我们已经能够实现返回文本给http请求,那么我们怎么返回HTML文件给浏览器呢?这时候我们就需要利用模板
一.设置模板目录
在项目下新建一个templates文件夹
在项目的settings.py文件下找到TEMPLATES列表项:
django学习007-MVT的T(模板)的使用DIR中添加目录BASE_DIR为当前项目的地址

    'DIRS': [os.path.join(BASE_DIR,"templates")],

django学习007-MVT的T(模板)的使用二,新建模板文件
在templates文件下新建html文件
django学习007-MVT的T(模板)的使用三,使用模板文件
使用过程:
1.加载模板文件
去模板目录下获取模板的html文件,得到一板 对象
2.定义模板上下文
向模板文件传送数据
3.模板渲染
得到一个标准的HTML内容
在view文件下index函数进行模板操作

from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader,RequestContext #引入模板类
# Create your views here.
#http://127.0.0.1:8000/index
#一个地址定义一个处理函数
def index (request):
    #进行处理,和M,T进行交互
    # 1.获取模板文件对象
    temp=loader.get_template("booktest/index.html")
    #2.定义模板上下文:给模板文件传数据
    context=RequestContext(request,{})
    #3.模板渲染:产生标准的HTML内容
    res_html=temp.render(context)
    return HttpResponse(res_html)

django学习007-MVT的T(模板)的使用打开浏览器刷新就可以看到模板文件使用成功
django学习007-MVT的T(模板)的使用四,调用系统函数进行三步操作
使用模板文件过程中都要进行上面的三步操作
(1.加载模板文件
2.定义模板上下文
3.模板渲染)
那么能不能写一个函数来完成这三步操作呢?系统已经给出那这个函数,gender()
from django.shortcuts import render
index函数直接可以改为:

def index (request):
	    return render(request,"booktest/index.html")

django学习007-MVT的T(模板)的使用效果和之前一模一样
五,在使用模板函数中传递数据
gender中传递字典数据

def index (request):
	return render(request,"booktest/index.html",{"content","hello world"})

在index.html中使用{{字典键值}}进行替换

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板文件</title>
</head>
<body>
<h1>这是一个模板文件</h1>
<p>这是模板变量:</p>
{{content}}
</body>
</html>

django学习007-MVT的T(模板)的使用刷新:

相关文章:

  • 2021-04-08
  • 2022-02-26
  • 2021-03-31
  • 2021-11-27
  • 2022-01-17
  • 2022-01-03
  • 2022-12-23
猜你喜欢
  • 2021-11-14
  • 2021-09-11
  • 2021-08-10
  • 2022-01-23
  • 2022-12-23
  • 2022-03-03
相关资源
相似解决方案