Flask render_template function

table of Contents

description

Syntax and parameters

return value

Usage example

There are no parameters in the template

Pass parameters to the template


 

description

The render_template() function is the flask function, which renders the given template context from the templates folder templates.

 

Syntax and parameters

import flask

flask.render_template(template_name, **context)

⚠️ The render_template() function needs to call the flask package

name meaning Remarks
template_name Template file name String parameter, cannot be omitted
context Template parameter A dictionary composed of template parameters and corresponding values, parameters that can be omitted

 

return value

str. The render_template() function returns the template text after replacing the template parameters.

 

Usage example

There are no parameters in the template

The template../templates/hello_world.html is as follows:

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

Example of using 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()

After running, enter http://127.0.0.1:5000/hello in the browser, and the results are as follows:

 

Pass parameters to the template

When there are variable parameters in the template, the render_template() function can pass parameters to the template:

The template../templates/for.html is as follows:

<!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>

Example of using 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()

After running, enter http://127.0.0.1:5000/ in the browser, and the results are as follows:

 

Guess you like

Origin blog.csdn.net/TCatTime/article/details/107660391