美文网首页
python+Django(2)—模版系统

python+Django(2)—模版系统

作者: 小盼盼_1 | 来源:发表于2020-09-20 10:54 被阅读0次

背景

借助于Django完成一个简单的web前端页面,views文件里面会将前端html语言和后端python代码写在一起,不利于维护。而且也背离了Django的核心:前后端分离。Django提供了一套模版系统可把页面设计html语言与python代码分开,方便维护。

模版系统

1.初级版

1)导入template模块,即from django import template

2)前端将html代码传入到template的Template对象,如t = template.Template('My name is {{ name }}.')

3)步骤2中变量的值【name】可通过template的Context类【可接受字典】进行映射,如c = template.Context({'name': 'Stephane'})

4)通过前面几个步骤,已经得到前端代码的html【有字符串&变量值】,但还缺少渲染步骤,此时可通过template的render对象将前端代码渲染出来【上下文】。如t.render(c)

2.进阶版

1)利用模板加载机制,将前端的html代码固定放在templates文件夹下

2)使用django.shortcuts模块中名为render()的函数替换前面步骤中创建Context和HttpResponse对象等,一行命令可达到相同的效果

注:同时存在多个app【即多个子模块】时,setting文件中可通过以下两种方式的设置达到A app查找到A app的templates文件下的html

方式一:

修改setting文件中TEMPLATES设置'DIRS': [os.path.join(BASE_DIR,'polls/templates')] 将所有的app的目录添加到列表,如A/templates B/templates C/templates 等

方式二:

1)修改setting文件中TEMPLATES设置'DIRS':[os.path.join(BASE_DIR,'templates')]

2)INSTALLED_APPS将所有的app的目录添加到列表中

INSTALLED_APPS=['django.contrib.admin','django.contrib.auth','django.contrib.contenttypes','django.contrib.sessions','django.contrib.messages','django.contrib.staticfiles','A','B','C']等

继承前端html模板

1.定义一个base.html文件,包含基本的html的模块

2.其他html引用的使用需要在头部增加{% extends %},表明会继承6.1中的base.html

注:需与html的一些模块标签结合使用

相关文章

网友评论

      本文标题:python+Django(2)—模版系统

      本文链接:https://www.haomeiwen.com/subject/rzpuyktx.html