-
模板位置
# 在应用中建templates目录,好处不需要注册,有多个应用的时候不能复用 # 第2种是放在工程的目录下,如果有多个应用,可以调用相同的页面, # 需要注册 # 需要修改项目的配置文件settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # 模板绝对路径 'APP_DIRS': True, # 是否在应用目录下查找模板文件 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Django 模板查找机制: Django 查找模板的过程是在每个 app 的 templates文件夹中找(不只是当前 #app 中的代码只在当前的 app 的 templates 文件夹中找)。
-
模板的渲染
# 1 loader加载 # 好处是可以加载1次模板,然后多次渲染 from django.template import loader # 导⼊loader def index(request): temp = loader.get_template('index.html') print(temp.__dict__) # 渲染模板,html源码 res = temp.render(context={'content': 'hello index'}) print(res) return HttpResponse(res) # 2 render from django.shortcuts import render render(request,templatesname,context=None) # 参数: # request: 请求对象 # templatesname:模板名称 # context:参数字典,必须是字典
Django——模板—模板位置+模板的渲染
最新推荐文章于 2020-09-16 13:42:43 发布