English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask Templates

Flask can return the output of a function bound to a URL in HTML format. For example, in the following script, the hello() function will use additional <h1>Tag rendering 'Hello World' .

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask
 app = Flask(__name__)
 @app.route('/')
 def index():
     return '<html><body><h1>'Hello World'</h1></body></html>'
 if __name__ == '__main__':
     app.run(debug = True)

However, generating HTML content from Python code can be very cumbersome, especially when variable data and Python language elements (such as conditions or loops) need to be placed. It is often necessary to escape HTML code.

It can utilize Jinja2Template engine technology, without needing to return hardcoded HTML from the function. As shown in the following code, HTML files can be rendered through the render_template() function.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask
 app = Flask(__name__)
 @app.route('/')
 def index():
    return render_template('hello.html')
 if __name__ == '__main__':
    app.run(debug = True)

Flask will try to find the HTML files in the templates folder in the same folder as the script. The directory structure of an application using templates is as shown below -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
app.py
 hello.py
     templates
         hello.html
         register.html
         ....

The term 'Web template system' refers to designing an HTML script that can dynamically insert variable data. A Web template system consists of a template engine, a data source, and a template processor.

Flask uses jinga2Web template engines. Web templates contain HTML syntax placeholders for variables and expressions (in this case, Python expressions), which are replaced with values when the template is presented.

The following code is in the template( templates) Save to folder: hello.html.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask HTTP request method handling</title>/title>
 </head>
    <body>
       <h1>Hello {{ name }}!<</h1>
    </body>
 </html>

Next, save the following code in app.pyin the file and run from Python shell -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template
 app = Flask(__name__)
 @app.route('/hello/<user>')
 def hello_name(user):
     return render_template('hello.html', name = user)}}
 if __name__ == '__main__':
     app.run(debug = True)

When the development server starts running, open the browser and enter the URL as - http://localhost:5000/hello/maxsu

The variable part of the URL is inserted at the placeholder {{name}}.

Jinja2The template engine uses the following delimiters to escape from HTML.

{% ... %} for multi-line statements {{ ... }} for printing expressions to the template {# ... #} for comments not included in the template output # ... ## for single-line statements

In the following example, conditional statements are demonstrated in the template. The URL rule of the hello() function accepts an integer parameter. It is passed to the hello.html template. Inside it, the received value of the number (mark) is compared (greater than or less than50), so conditional rendering output was executed in HTML.

The Python script is as follows -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template
 app = Flask(__name__)
 @app.route('/hello/<int:score'>
 def hello_name(score):
     return render_template('hello.html', marks = score)
 if __name__ == '__main__':
     app.run(debug = True)

Template file: hello.html The HTML template script is as follows -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Template Example</title>
 </head>
    <body>
       {% if marks}50 %}
       <h1>Passed the exam! </h1>
       {% else %}
       <h1>Failed the exam! </h1>
       {% endif %}
    </body>
 </html>

Please note that the conditional statement if-else and endif are enclosed in delimiters {%...%}

Run the Python script and access the URL => http://localhost/hello/60, then access http://localhost/hello/59is opened in the browser, conditional HTML output can be viewed.

Python loop structures can also be used within the template. In the following script, when the URL => http:// localhost:5000/When 'result' is called, the result() function sends the dictionary object to the template file: results.html .

result.html The template part uses a for loop to present the key-value pairs of the dictionary object result{} as table cells in the HTML table.

Run the following code in the Python shell.

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from flask import Flask, render_template
 app = Flask(__name__)
 @app.route('/result)
 def result():
     dict = {'phy':59'che':60, 'maths':90
     return render_template('result.html', result = dict)}
 if __name__ == '__main__':
     app.run(debug = True)

Save the following HTML script as a template folder ( templates) of the template file: result.html .

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask Template Example</title>
 </head>
    <body>
       <table border = 1>
          {% for key, value in result.items() %}
             <tr>
                <th> {{ key }} </th>/th>
                <td> {{ value }} </td>/td>
             </tr>
          {% endfor %}
       </table>
    </body>
 </html>

Here, the Python statement corresponding to the For loop is contained in {%...%}, and the key and value expressions are placed in {{}}.

After the development starts running, open http: in the browser.//localhost:5000/result to obtain the following output.