推荐答案
在 Flask 中,可以通过 render_template 函数将数据传递给模板。具体步骤如下:
定义视图函数:在视图函数中,使用
render_template函数渲染模板,并通过关键字参数传递数据。// www.javascriptcn.com code example from flask import Flask, render_template app = Flask(__name__) @app.route('/') def index(): user = {'username': 'John Doe'} posts = [ {'author': 'Jane Doe', 'body': 'Beautiful day in Portland!'}, {'author': 'John Doe', 'body': 'The Avengers movie was so cool!'} ] return render_template('index.html', title='Home', user=user, posts=posts)在模板中使用数据:在模板文件(如
index.html)中,可以使用 Jinja2 模板语法访问传递的数据。// www.javascriptcn.com code example <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <h1>Hello, {{ user.username }}!</h1> <ul> {% for post in posts %} <li>{{ post.author }} says: {{ post.body }}</li> {% endfor %} </ul> </body> </html>
本题详细解读
1. render_template 函数
render_template 是 Flask 中用于渲染模板的核心函数。它接受模板文件名作为第一个参数,并可以通过关键字参数传递任意数量的数据到模板中。
render_template('template_name.html', key1=value1, key2=value2, ...)2. 模板引擎 Jinja2
Flask 使用 Jinja2 作为默认的模板引擎。Jinja2 允许在 HTML 中嵌入 Python 代码,通过 {{ }} 输出变量,通过 {% %} 控制逻辑。
- 变量输出:
{{ variable }}用于输出变量的值。 - 控制结构:
{% for item in list %}和{% if condition %}等用于控制模板的逻辑流程。
3. 数据传递示例
在视图函数中,可以通过字典、列表等数据结构传递数据到模板。模板中可以访问这些数据,并根据需要进行渲染。
@app.route('/')
def index():
user = {'username': 'John Doe'}
posts = [
{'author': 'Jane Doe', 'body': 'Beautiful day in Portland!'},
{'author': 'John Doe', 'body': 'The Avengers movie was so cool!'}
]
return render_template('index.html', title='Home', user=user, posts=posts)在模板中,可以通过 {{ user.username }} 访问用户名,通过 {% for post in posts %} 遍历帖子列表并输出内容。
4. 模板文件结构
模板文件通常存放在 templates 目录下。Flask 会自动在该目录下查找模板文件。例如,index.html 文件应位于 templates/index.html。
// www.javascriptcn.com code example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ title }}</title>
</head>
<body>
<h1>Hello, {{ user.username }}!</h1>
<ul>
{% for post in posts %}
<li>{{ post.author }} says: {{ post.body }}</li>
{% endfor %}
</ul>
</body>
</html>通过这种方式,Flask 可以轻松地将数据从视图函数传递到模板,并在模板中进行渲染。