Flask render_template函数

目录

描述

语法及参数

返回值

使用示例

模板中没有参数

给模版传递参数


描述

render_template()函数是flask函数,它从模版文件夹templates中呈现给定的模板上下文。

语法及参数

import flask

flask.render_template(template_name, **context)

⚠️ render_template()函数需要调用flask包

名称 含义 备注
template_name 模板文件名 字符串型参数,不可省略
context 模板参数 由模板参数和对应的值组成的字典,可以省略的参数

返回值

str。render_template()函数返回替换模板参数后的模板文本。

使用示例

模板中没有参数

模板../templates/hello_world.html如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello world</title>
</head>
<body>
    <h1> Hello World! </h1>
</body>
</html>

render_template使用示例:

import flask

app = flask.Flask(__name__)

@app.route("/hello")
def hello():
    return flask.render_template("hello_world.html")

if __name__ == '__main__':
    app.run()

运行后在浏览器中输入http://127.0.0.1:5000/hello,结果如下:

给模版传递参数

当模板中存在可变参数时,render_template()函数可以为模板传递参数:

模板../templates/for.html如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jinja2 Circulation Control</title>
</head>
<body>
    <h1> {
   
   {product}} list: </h1>
    <ul>
    {% for product in products %}
        <li>{
   
   {product}}</li>
    {% endfor %}
    </ul>
</body>
</html>

render_template使用示例:

import flask

app = flask.Flask(__name__)


@app.route("/")
def index():
    products = ["iphoneX", "MacBook Pro", "Huawei"]
    kwargs = {
        "products": products
    }
    return flask.render_template("for.html", **kwargs)


if __name__ == '__main__':
    app.run()

运行后在浏览器中输入http://127.0.0.1:5000/,结果如下:

猜你喜欢

转载自blog.csdn.net/TCatTime/article/details/107660391
今日推荐