render template 用法
时间: 2023-07-21 13:40:09 浏览: 61
render_template 是 Flask 框架中一个非常重要的函数,用于渲染模板文件并生成响应。
render_template 函数的基本用法如下:
```
from flask import render_template
@app.route('/hello')
def hello():
return render_template('hello.html', name='World')
```
上述代码中,我们定义了一个路由 /hello,当用户访问该路由时,会调用 hello 函数。hello 函数使用 render_template 函数来渲染名为 hello.html 的模板文件,并将参数 name 的值传递给该模板文件。
此外,我们还可以在模板文件中使用 Jinja2 模板引擎来动态生成 HTML 页面。例如,我们可以在 hello.html 模板文件中添加如下代码:
```
<!doctype html>
<html>
<head>
<title>Hello, {{ name }}!</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
```
上述代码中,我们使用 {{ name }} 语法来表示将动态生成的值插入到 HTML 页面中。在上面的例子中,{{ name }} 会被替换为 World,最终生成的 HTML 页面为:
```
<!doctype html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<h1>Hello, World!</h1>
</body>
</html>
```
总之,使用 render_template 函数可以方便地将模板文件渲染为 HTML 页面,并实现动态生成 HTML 内容的功能。