首页 > 编程 > Python > 正文

Django框架模板文件使用及模板文件加载顺序分析

2019-11-25 12:51:37
字体:
来源:转载
供稿:网友

本文实例讲述了Django框架模板文件使用及模板文件加载顺序。分享给大家供大家参考,具体如下:

模板功能

产生html,控制页面上产生的内容。模板文件不仅仅是一个html文件。

模板文件包含两部分内容:

1.静态文件:css,js,html

2.动态内容:用于动态的去产生一些网页内容,通过模板语言产生

模板文件的使用

通常是在视图函数中使用模板产生html内容返回给客户端

a,加载模板文件 loader.get_template

获取模板文件的内容,产生一个模板对象

b,定义模板上下文 RequestContext

给模板文件传递数据

c,模板文件渲染产生的html页面内容 render

用传递的数据替换相应的变量,产生一个替换后的表中html内容

from django.shortcuts import renderfrom django.template import loader,RequestContextfrom django.http import HttpResponse# Create your views here.def my_render(request,template_path,context={}):  # 1.加载模板文件,获取一个模板对象  temp = loader.get_template(template_path)  # 2.定义模板上下文,给模板传递数据  context = RequestContext(request, context)  # 3.模板渲染,产生一个替换后的html内容  res_html = temp.render(context)  # 4.返回应答  return HttpResponse(res_html)# /indexdef index(request):  # return my_render(request,'booktest/index.html') 这是自己封装的render  # 其实Django已经封装好了,可以直接使用  return render(request,'booktest/index.html')

模板文件的加载顺序

1.首先去配置的模板目录下找模板文件

2.去INSTALL_APPS下面的每个应用去找模板文件,前提是应用中必须有templates文件夹

希望本文所述对大家基于Django框架的Python程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表