Flask Web Framework – Render Templates

Published by BrighterBees on

In the previous Article we have read about URL building and HTTP Methods. Next we will discuss about rendering templates of HTML in this Article.

It is possible to return the output of a function bound to a certain URL in the form of HTML. For instance, in the following script, home() function will render “Hello World” with <h1> tag attached to it.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def home():
    return '<html><body><h1>Hello World</h1></body></html>'

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

However, generating HTML content from Python code is cumbersome, especially when variable data and Python language elements like conditionals or loops need to be put. This would require frequent escaping from HTML.

This where one an take advantage of Jinja2 template engine, on which Flask is based. Instead of returning hardcode HTML from the function, a HTML file can be rendered by a rendered_template() function.

Make Folder structure described below –

Application Folder
        - app.py
        - templates
               - home.html

Write the code in app.py –

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
    return render_template('home.html')

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

Flask will try to find the HTML file in the templates folder, in the same order in which script is present above ☝.

Web Templating System

The term ‘Web Templating System’ refers to designing as HTML script in which the variable data can be inserted dynamically. A web template system comprises of a template engine, some kind of data source a and a template processor. Flask uses jinja2 template engine. A web template contains HTML syntax interspersed placeholders for variable and expressions (in this case Python expressions) which are replaced values when the template is rendered.

Save the following code in home.html in the templates folder.

<!DOCTYPE html>
<html>
<head>
	<title>Home</title>
</head>
<body>
	<h1> Hello {{ name }}! </h1>
</body>
</html>

Next, run the following code from Python shell or CMD.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/home/<user>')
def home(user):
    return render_template('home.html' , name = user)

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

As the development server starts running, open the browser and enter URL as – http://localhost:5000/home/brighterbees

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

The Jinja2 template engine uses the following delimiters for escaping from HTML.

  • {% …. %} for Statements
  • {{ …. }} for Expressions to print to the template output.
  • {# …. #}} for comments not included in the template output.
  • # …. ## for Line Statements.

If-else Statement in jinja2

In the following example, use of conditional statement in the template is demonstrated. The URL rule to the home() function accepts the integer parameter. It is passed to the home.html template. Inside it, the value of number received (marks) is compared (greater or less than 50) and accordingly HTML conditionally rendered.

The Python code is as follows –

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/home/<int:score>')
def home(score):
    return render_template('home.html' , marks = score)

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

HTML template code of home.html is as follows –

<!DOCTYPE html>
<html>
	<head>
		<title>Marks</title>
	</head>
	<body>

		{% if marks > 50 %}
		<h1> Your result is pass! </h1>
		{% else %}
		<h1> Your result is fail! </h1>
		{% endif %}

	</body>
</html>

Note that the conditional statements if-else and endif are enclosed in delimiter {%..%}.

Run the Python code and visit URL http://localhost/home/70 and then http://localhost/home/40 to see the output of HTML changing conditionally.

For Loop Statement in jinja2

The Python loop constructs can also be employed inside the template. In the following code, the result() function sends a dictionary object to template results.html when URL http://localhost:5000/result is open in the browser.

The template part of result.html employs a for loop to render key and values pairs of dictionary object result{} as cells of an HTML table.

Run the following code from Python Shell or CMD by writing Python app.py.

Application Folder
        - app.py
        - templates
               - home.html
               - result.html
from flask import Flask, render_template
app = Flask(__name__)

@app.route('/home/<int:score>')
def home(score):
    return render_template('home.html' , marks = score)

@app.route('/result')
def result():
	dict = {'Physics':60 , 'chemistry':60 , 'Maths':90 } 
	return render_template('result.html' , result = dict)


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

Save the following HTMO code as result.html in the templates folder.

<!DOCTYPE html>
<html>
	<head>
		<title>Result</title>
	</head>
	<body>

		<table border="1">
			<h2>Result Table </h2>
			{% for key, value in result.items() %}
			<tr>
				<th>{{ key }} </th>
				<td> {{ value }} </td>

			</tr>
			{% endfor %}
		</table>
	</body>
</html>

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

So finally we have discussed templates rendering, jinja2 statements and some examples over it. I think it will help you. If you have any doubt regarding this then comment below.

connect with the author on LinkedIn.

visit our website brighterbees for such interesting study stuff and more about flask.

you can also access our blog series on cloud computing.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

STAY CONNECT WITH US