In this post we will learn about using template engine in flask in flask. Its pretty easy.

In this post we are going to cover the following things:

  1. For loops in templates.
  2. If else contions in templates.
  3. Filters
  4. Inheritance and Blocks
  5. Comments

For Loops in Templates.

For loops can be similarly like normal python for loop but with a small twist. Let’s a example,


@app.route("/all")
def GetAllfruits():
	fruits = ["Apple", "Banana", "Mangoes", "Grapes", "Kiwi", "Orange"]
	context = {
		'fruits' : fruits,
	}
	return render_template("template.html", fruits=fruits)

<ol>
{% for fruit in fruits %}
	<li> {{ fruit }} </li>
{% endfor %}
</ol>

As you may have seen in the above the code block that we use {% %} , i.e. curly brackets with percent signs to write ontitional statements and it is the format we use in temlates.

You must have seen that template loop syntrax is similar to that of python with a exception that it need a starting and closing block. For each fruit in fruits all the code inside the for loop tags would run.

If Else Conditons in templates.

Using if else conditions in templates is super simple. Let’s first see an exmple,


@app.route("/all")
def GetAllfruits():
	fruit = True
	context = {
		'fruit' : fruit,
	}
	return render_template("template.html", fruit=fruit)

{% if fruit %}
	<h3> Its healthy. </h3>
{% elif someOtherCondition %}
	<h3> Other Condition Result </h3>
{% else %}
	<h3> Its not healthy. </h3>
{% endif %}

You can also do it like this,


{% if fruit %}
	<h3> Its healthy. </h3>
{% endif %}

In the first example we have seen an if - else statement it can be nested as mush as you want you may see that we can even use elif operator in the code above, and in second code block we have see a simple if statemnt, even it can be nested by the way you can use any template tag any where in the template with only one exception that is of include statement about which you can read below.


Filters

Filters can be used in templates to make life easy, filters can be used on an varible by using pipe symbol ( | ) next to it, in this exmple we have the value of vaible fruits = “Mango Apple”, now let’s see how to use it.


{{ fruits | upper }}

It will return MANGO BANANA. This filter can be nested,


{{ fruits | trim | upper }}

It will return MANGOBANANA. You can also create custom filters in this way,

@main.template_filter('containsbanana')
def ContainsBanana(value):
	if 'BANANA' in value.upper():
		return True

and use it this way,

{{ fruits | containsbanana }}

Inheritiance and Blocks

In this section we will see temlpate inheritiance and and how to use blocks in the templates. You must have this question in your mind why to use it, the answer is,

  1. It helps to split code.
  2. Increases mantaniblity.
  3. Makes it easy to find bugs.
  4. Canges can be made at one place and applied to all the templates.
  5. and so on..

We will start by makeing a base template, at least this is the way i do it, we will create a base template and we will inherit from it in a sub-template in this way we can split the code as well learn blocks,

base.html


<!DOCTYPE html>
<html>
<head>
	<title>{% block title %}{% endblock title %}</title>
</head>
<body>
	{% block body %}{% endblock body %}
</body>
</html>

You may have seen the way we create block the syntrax is {% block bock_name %}{% endblock bock_name %}, now you may ask how to use these block and it is pretty simple. We will first incude by extends tag this in a sub-template.

Note : In this template we are considering that base.html is in the templates subfolder.

Now let’s include this template in sub-template.html which may be anywhere in templates directory.

{% extends "base.html" %}
{% block title %}
	This is page title.
{% endblock title %}
{% block body %}
	<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>
{% endblock body %}

Here you may have seen extends have no closing tag. The syntrax of extends is as follows {% extends "path/to/file.html" %}. YOu can use any template to inherit from it. Just note that write the path in "" of extends in releative to templates directory.

Now Lets discuss about those blocks , their syntrax is {% block blockname %}{% block blockname %} in file you inherit from and {% block blockname %} <p> Your content here. </p> {% block blockname %}, and this example will render as following.


<!DOCTYPE html>
<html>
<head>
	<title>This is page title.</title>
</head>
<body>
	<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
	tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
	quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
	consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
	cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
	proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>
</body>
</html>

Comments in Templates

Now let’s discuss comments in flask templates , for you it may / may not be important but it is a pretty important part while you manintani code in log run. Let’s first see its syntrax and it is {# your comment or code goes here #} , or you are like me who comments code to find problems and fix it here is how it works,

{#
	{% if fruit %}
		<h3> Its healthy. </h3>
	{% elif someOtherCondition %}
		<h3> Other Condition Result </h3>
	{% else %}
		<h3> Its not healthy. </h3>
	{% endif %}
#}

None of the code in {# #} will run and will not be even visible in the rendered templates.


Bonus

How to change default templatate directory in flask ?
from flask import Flask
app = Flask(__name__, template_folder='.././path/to/template')

It is as simple as adding template_folder kwarg to Flask when creating app instance.

Hope you like it. 😍


Check out next part of this series at Get and Post requests in Flask - Flask For Noobs 🧪 or check previous part Templating in Flask. - Flask For Noobs 🧪.