企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] 之前我们在视图函数里返回的是一个HttpResponse类的实例,但是我们的网页不可能只有HttpResponse返回的一句话,我们也不可能每次需要改页面样式都要操作python代码。 django 对这个问题提供了一个很好的解决方案,叫做模板系统。django 要我们把页面样式写到一个文件里,然后 django 自己会去读取这个文件,再把读取到的内容传给 HttpResponse。 在之前创建的 `book` 应用下新建 目录 `template` ,模板相关代码会在此做演示。 ## 配置 在 `settings.py` 文件中 `TEMPLATES` 项指定了如何渲染模板。 ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] ``` APP_DIRS项被设置为了True,代表django会在每个app目录内寻找 `templates` 子目录,而我们的 `templates` 目录是放在 `book` 应用下的,所以不需要我们进行DIRS的设置。而如果templates要放在其他文件夹下,则需要设置DIRS项。 ## 使用 ### 1. 创建模板 在 `templates` 目录下新建文件 `index.html` ,写入代码: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ book }} </body> </html> ``` 类似 `{{ }}` 这样的格式叫做模板标签,会在后边有详细的讲解。 ### 2. 创建视图函数 在 `book` 目录下的 `views.py` 文件下创建视图函数。 ``` from django.http import HttpResponse def index(request): template = loader.get_template('index.html') context = {"book": "边城浪子"} return HttpResponse(template.render(context, request)) ``` 新建 `urls.py` 文件配置路由 ``` from django.conf.urls import url from . import views urlpatterns = [ url(r'^index/', views.index, name="book") ] ``` 在项目目录下的 `urls.py` 注册子路由 访问路径 [http://127.0.0.1:8000/book/index/](http://127.0.0.1:8000/book/index/) k可以看到返回的结果。 #### render 由上边的示例可以看出,使用模板有三个步骤 1. 获得模板 2. 加载上下文 3. 渲染模板,返回响应 这三个步骤是很常用的步骤,所以django为我们提供了快捷完成的方式 `render`。 导入包: ``` from django.shortcuts import render ``` 修改视图函数 ``` from django.shortcuts import render def index(request): context = {"book": "边城浪子"} return render(request, 'index.html', context) ``` render的常用参数: - request:固定参数 - template:模板文件的路径 - context:context数据 其他参数: - content_type: 生成的文档要使用的MIME 类型。默认为DEFAULT_CONTENT_TYPE 设置的值。 - status: http的响应代码,默认是200. - using: 用于加载模板使用的模板引擎的名称。