Flask Tutorial Python — Flask Templates
Tags: Python Programming, Python Flask, Python3, Flask, Python

In this Python Flask tutorial, I cover the basics of the Flask Templates along with other important concepts such as Flask render_template, Flask url_for, Flask g and session object, concerning Flask Application context and Flask Request context.

As mentioned in the tutorial on The Basics of Flask Framework, Flask templates are files that consist of some static data and placeholders for Dynamic Data.

Flask populates the placeholders in templates with the required HTML so that when a browser sends a request on a particular route then the web server can reply with an appropriate response.

Flask Template Tags

Flask Template is an HTML file with three types of tags:-

A pair of two curly braces i.e. {{ }} — One can use variables and expressions inside these template tags. For example, one can print the value of a variable or evaluate expressions. In other words, anything inside these tags is evaluated and printed out to the final HTML. A pair of curly braces with percentage symbol i.e. {% %} — We use Flask template language-specific words in these tags. For example, we use if, for, block, extend, endif, endfor, endblock, etc. A pair of curly braces with hash symbol i.e. {# #} — We use these tags to mention comments.

In addition to these tags, A template file can have usual HTML tags for elements such as ordered list, unordered list, spans, paragraphs, etc.

Flask Template Variables

In templates, one can use variables as in other languages. These variables should be available in the application or the request context of the Flask Application.

{# evaluating variables and expressions #}

<li> {{ num }} — {{ num + 1 }} </li>

For example, the above code will print a list item with the value of num, and one added to it, separated by a dash.

Moreover, one can use Flask url_for, Flask g and session objects inside these tags.

Flask Template If

In Templates, one can use conditional if statements as shown below.

{# conditional statement #} {% if num is number and num is gt 0 %} {# evaluating variables and expressions #}

<li> {{ num }} — {{ num + 1 }} </li> {% else %} {# code of else block #} {% endif %}

For example, one can print the value of num and related expressions inside the list item based on a condition such as whether a variable num is a number and greater than zero.

Additionally, one can use {% else %} to print out other values if the condition did not satisfy. Notice the use of {% endif %} to end the if statement.

Flask Template For

Similar to the if construct, one can also use a loop inside the templates. Look at the example below.

{# For loop construct #}

{% for num in numbers %}

<ul> {# other statement for creating list items #} </ul> {% endfor %}

In this example, using a FOR loop, an unordered list of list items is created with values of num based on the conditions mentioned inside the IF construct.

Flask Template Built-In Functions, Tests, and Filters

Flask template has a lot of built-in functions, tests, and filters. One can mention all builtin functions, tests, and filters inside of {% %}.

An example of format function with the use of a built-in filter string using a | on a variable.

<li> {{ "found {}, which is not a number or not greater".format(num|string) }}</li>

An example of a built-in function gt(greater than) in an if conditional statement.

{% if num is number and num is gt 0 %}

For details look at the following links.

Flask Template Extends

Usually, an application’s content is distributed into multiple templates for better internal information management and maintenance. Therefore, one can use extends keywords to inherit the features of the parent template.

For example, look at the use of the keyword extends to inherit features of a base template as shown below.

{% extends "my_base.html" %}

In the above-given code, a template is inheriting features of a template called my_base.html by using the keyword extends.

Flask Template Block

Using the keyword block, one can override the content of the inherited template.

For example, once can override the content of a block template_header in mybase.html with its own content as shown below.

{% block template_header %}

{{ template_h3 }}

{% endblock %}

Now, look at the block content. Notice the use of the keyword super to print contents from my_base.html.

{% extends "my_base.html" %} {% block template_header %}

{{ template_h3 }}

{% endblock %} {% block content %} {{ super() }}

{% endblock %}

Flask Template Example Step By Step

Before you read further, to follow through the code examples with the skeleton project layout, clone the Github repository, and checkout its flask-template branch.



git checkout flask-template git clone https://github.com/theflaskbooks/flask-tutorial git checkout flask-template

If you have already cloned it, then open the command line or terminal and change into the flask-tutorial directory.

Now, let us implement all the discussed Flask Template concepts in an example.

However, complete the following prerequisites if you are continuing from the previous two tutorials in this series.

Install Prerequisites

Let us install Flask-DebugToolbar and create an admin user.

Install Flask-DebugToolbar

Before learning about Flask Templates, I want you to install a very important Flask extension called Flask-DebugToolbar.

pip install Flask-DebugToolbar

Now enable it by using the below lines of code and adding them to the init.py inside the app directory.

from flask_debugtoolbar import DebugToolbarExtension # other application code

# Use the below-given statements just after instantiating the Flask application

# object i.e. after app=Flask(__name__) app.debug = True

app.config.from_object("config") # initialize debugtoolbar after loading the values from config.

debugtoolbar = DebugToolbarExtension(app) ## more application code.

I explicitly specify the debug property of the app object to True and initialize the DebugToolbarExtension by passing the app object to it.

The Flask Debug Toolbar intercepts a redirect(302) for debug viewing purposes. You can click the shown link to continue with the redirect as normal. If you’d like to disable this feature, you can set the config variable DEBUG_TB_INTERCEPT_REDIRECTS to False.

Now in the command line or terminal activate the virtual environment, go into myapp directory and run the development server.

cd myapp/

python run.py

Now navigate to http://localhost:8080/, using your browser, and look for FDT (Flask DebugToolbar) plugin at the right-hand side of the browser. The expanded view of FDT looks like the one shown below.

Flask-DebugToolbar Plugin

Flask DebugToolbar is quite useful in debugging a Flask application and inspecting the values of HTTP headers, Request variables such as GET and POST variables, Configuration values as mentioned in config.py, and other important details.

Let us not wait anymore to learn about Flask Templates. But just so we can securely access those templates, let us create an admin user.

Create an Admin User

Stop the development server if it is already running, and create an admin user, using the below-given command from the project’s root directory myapp.

flask fab create-admin

For development, keep default values for the user other than the password.

Once the admin user is created, run the development server again.

Step 1. Create Flask Templates

Create a file called my_base.html and enter the following given code into it, and save it.

{% extends "appbuilder/base.html" %} <h3>Hello from {% block template_header %} Base Template {% endblock %} </h3> {% block content %}

<p> Content from Base Template </p>

{% endblock %}

Save my_base.html file.

Create a file called my_template.html inside the templates directory, use the below-given code, and paste it into the file.

{% extends "my_base.html" %} {% block template_header %}

{{ template_h3 }}

{% endblock %} {% block content %} {{ super() }}

{# For loop construct #}

{% for num in numbers %}

<ul> {# conditional statement #} {% if num is number and num is gt 0 %} {# evaluating variables and expressions #}

<li> {{ num }} — {{ num + 1 }} </li> {% else %} {# An example use of built-in function and a filter #}

<li> {{ "found {}, which is not a number or not greater".format(num|string) }}</li> {% endif %} </ul> {% endfor %} {% endblock %}

Save my_template.html file.

Step 2. Create A View To Render Flask Template

Open file views.py and use the below-given code to create a view called MyTemplateView and map it to the route my_template as shown with the @expose decorator function.

from flask_appbuilder import BaseView, expose, has_access class MyTemplateView(BaseView): default_view = "my_template" @expose("/my_template")

@has_access

def my_template(self): numbers = [0, 1, 2, 3, 'a'] return self.render_template(

"my_template.html",

template_h3="My Flask Template",

numbers=numbers

) ## Add views to appbuilder

appbuilder.add_view(MyTemplateView, "MyTemplate", category="FlaskTutorial") ## Add a view as sub-menu under a category

appbuilder.add_link("Method2", href='/mytemplateview/method2', category='FlaskTutorial')

Save views.py file.

Now navigate to http://localhost:8080/ using the browser, and log in to the application using admin user details.

Remember to click on the route on the Flask-DebugToolbar intercept page whenever there is a redirection, if you have not already disabled the intercepts.

Click on the MyTemplate sub-menu under FlaskTutorial Menu and you will see the output like the one displayed below.

MyTemplate sub — menu

Summary

In this article, I provided details on the concepts concerning Flask Templates. I discussed conditional and Loop constructs such as IF and FOR, Flask Template tags, variables, inheritance using keywords such as extends and blocks.

I also implemented the discussed concepts in a step by step format to create templates and render those with Flask Views with the help of Flask-Appbuilder. Additionally, I explained the benefits of Flask-DebugToolbar along with an example of creating an admin user.

In my next tutorial, I will cover the Flask Framework with MySQL Database.