def __init__(self,template_string,origin=None,name=None,engine=None)它只有一个必填的参数:字符串表示的模板代码。
BookStore/templates路径创建模板文件夹 templates,在 settings.py 配置文件中有一个 TEMPLATES 变量,如下所示:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [], #指定模板文件的存放路径
'APP_DIRS': True, #搜索APP里面的所有templates目录
'OPTIONS': {
'context_processors': [ #context_processors 用于配置模板上下文处理器
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
其中每一项释义如下所示:
'DIRS': [os.path.join(BASE_DIR, 'templates')]
from django.template import loader
# 1.通过loader加载模板
t = loader.get_template("模板文件名")
# 2.将t转换成HTML字符串
html = t.render(字典数据)
# 3.用响应对象将转换的字符串内容返回给浏览器
return HttpResponse(html)
方式二:使用 render 方法直接加载并响应模板from django.shortcuts import render return render(request,'模板文件名', 字典数据)下面我们对上述两种方式分别来说明:
#方式一
from django.template import loader # 导入loader方法
from django.shortcuts import render #导入render 方法
def test_html(request):
t=loader.get_template('test.html')
html=t.render({'name':'c语言中文网'})#以字典形式传递数据并生成html
return HttpResponse(html) #以 HttpResponse方式响应html
#方式二
from django.shortcuts import render #导入reder方法
def test_html(request):
return render(request,'test.html',{'name':'c语言中文网'})#根据字典数据生成动态模板
然后在 templates 目录下创建 test.html 文件并在其中添加如下代码:
<p style="font-size:50px;color:red">{{name}},网址是<a href="http://c.biancheng.net/">http://c.biancheng.net/</a></p>
提示:{{name}} 属于 django 模板语言的语法,代表一个变量,在后续章节我们会讲解。
最后在 BookStore/urls.py 文件的 urlpatterns 列表中为视图函数 test_html() 配置路由映射关系,如下所示:
urlpatterns = [ path('admin/', admin.site.urls), path('test/',views.test_html), ]
从上述过程我们不难体会 Django 视图函数的实现流程。首先定义了视图函数 test_html(),然后在 templates 文件夹中新建了 test.html 文件,使用它作为模板文件;最后我们配置了视图函数的路由映射关系,以上步骤完成后,我们可以通过访问 127.0.0.1/test 得到如下展示页面:render(request, template_name, context=None, content_type=None, status=None, using=None)以下每个参数的含义如下所示:
text/html : HTML 格式
text/plain :纯文本格式
text/xml : XML 格式
image/gif :gif 图片格式
image/jpeg :jpg 图片格式
image/png:png 图片格式
application/xhtml+xml :XHTML 格式
application/xml: XML 数据格式
application/atom+xml :Atom XML 聚合格式
application/json: JSON 数据格式
application/pdf:pdf 格式
application/msword :Word 文档格式
application/octet-stream : 二进制流数据(如常见的文件下载)
application/x-www-form-urlencoded :form 表单数据被编码为 key/value 格式发送到服务器(表单默认的提交数据的格式)。
multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式
版权说明:Copyright © 广州松河信息科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州松河信息科技有限公司 版权所有