Flask render_template函数

12 篇文章 2 订阅

目录

描述

语法及参数

返回值

使用示例

模板中没有参数

给模版传递参数


描述

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/,结果如下:

  • 15
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值