详解Django的 render() 函数:渲染模板

  • Post category:Python

render() 是Django框架中用于将数据填充到模板中,并返回生成的HTML响应的函数。它可以将一个渲染上下文(也可以是其他参数,如请求和视图名称)作为关键字参数,并用此参数将模板和数据合并在一起。下面是详细讲解render()函数的作用与使用方法:

1. 作用

render()函数主要用于将给定数据(通常是从数据库中检索到的)合并到指定的HTML模板中,并将合并后的HTML响应返回给客户端。它还根据需要渲染布局和包括其他子模板。此外,还可以通过设置HTTP头和cookies来自定义响应内容。

2. 使用方法

首先,在视图函数中导入render函数,例如:

from django.shortcuts import render

然后,您需要为数据创建一个字典或查询集,与模板变量所需的键相对应。

接下来,将模板名称(或模板名称的列表)传递给render()函数。例如:

def my_view(request):
    # 假设您从数据库中检索到以下数据
    data = {
        'name': 'John',
        'age': 25,
        'hobbies': ['running', 'hiking', 'reading']
    }
    # 需要传递给模板中的数据以字典形式传递
    return render(request, 'my_template.html', {'data': data})

模板名称可以是模板的相对或绝对路径。如果没有提供模板名称或模板名称列表,则默认使用文件名为“/_detail.html”的模板。

默认情况下,Django将在您的应用程序中查找模板。如果要在多个应用程序之间共享模板,则可以在模板加载器中注册任意数量的目录;

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'APP_DIRS': True,
    'DIRS': [
        '/path/to/my/templates',
        '/other/path/to/my/templates',
    ],
},
]

除了要渲染的数据和要使用的模板名称之外,还可以提供其他一些参数:

content_type

content_type参数可以设置HTTP响应类型,默认情况下,它将使用text/html。例如:

return render(request, 'my_template.html', {'data': data}, content_type='application/xhtml+xml')

status

status参数允许您设置HTTP状态代码,例如“200 OK”或“404 Not Found”。例如:

return render(request, 'my_template.html', {'data': data}, status=404)

下面是两个实际使用场景的例子:

例子1:渲染一个模板

假设您有一个模板文件 /path/to/my_template.html,其中包含以下HTML:

<!DOCTYPE html>
<html>
<head>
    <title>{{ title }}</title>
</head>
<body>
    <h1>{{ heading }}</h1>
    <p>Welcome to my website!</p>
</body>
</html>

要使用render()函数渲染该模板并将数据传递给它,请按如下方式编辑视图函数:

def my_view(request):
    context = {
        'title': 'My Website',
        'heading': 'Welcome to my website!'
    }
    return render(request, '/path/to/my_template.html', context)

该视图函数将首先创建一个包含标题和标题的字典( context ), 然后使用render()函数将指定的模板和未自定义的上下文一起呈现。当 Django遇到{{ title }}{{ heading }}时,它将在字典中查找相应键( 对应的是 titleheading), 填充模板中的占位符并返回HTML响应。

例子2:传递数据

假设您从数据库中检索到以下数据:

def my_data_view(request):
    data = {'name': 'John', 'age': 25, 'gender':'Male'}
    return render(request, 'my_template.html', {'data': data})

然后您的模板可以使用以下代码片段进行调用:

<body>
    <p>Hi, {{ data.name }}! Your age is {{ data.age }} and you are {{ data.gender }}</p>
</body>

模板中的 {{ data.name }} 和{{ data.age }} 变量本质上将从数据对象中提取出键为 name 和 age 的值。

以上就是关于render()函数的作用与使用方法的完整攻略。