Flask Templates

Set up Templates in Python Flask

This article is going to explain how Templates in the Flask web framework are set up and how to use them. Let's begin!

What are Templates?

Temlates are files used to show content on the website pages. These files are the CSS, JS, and JTML. Templates help to showcase the design of a website page. Therefore, all the websites contain the Front-end (consisting of Templates) and Back-end (Flask framework codes and applications).

Related course: Create Web Apps with Python Flask

Web Templating System

The web templating system consists of a template processor, template engine, and data source. Numerous times, the website help to display data from the DB on their website page. With the help of HTML and DB files plus the use of Template languages website information is displayed on the webpage.

Jinja2 is a template engine which the Flask uses as a default engine. More explanation will be some in the next section.

Jinja Templating Language (JTL)

The template engine renders a template language that helps to add information into the HTML files.

Jinja2 is a unique templating language for python which is developed to make work easier for designers. The Jinga Templating Language is designed after Django's Template Let's study the syntax of this template language. They are four types of this Syntax: Type Syntax

Statement Tags

{% %}: {% if…..else %} – {% endif %}

Variable Tags

{{ }}: {{ variable }}

Commenting Tags

{#…..#}: {# comment ….para #}

Line Comment Tags

#: #comment line

Adding Templates In Our Application

Flask inquiries for templates compiled in a folder named – templates establish beside the major application file. Create a folder before the subsequent section.

Contents of the templates folder

  • render_template() function You can use the command render_template() to render template on the Flask application. The syntax is:
render_template('<template_file_name.html>', variables = <values> )

Coding our Flask app Add the code into your file flask main file ( revisit the introduction to the flask for more information)

from flask import Flask, render_template

app = Flask(__name__)

def blogs(id):
    return render_template('blog.html', number=id)

app.run(host='localhost', port=5000)

Formulate the template blog.html:

        <h1>This is a Blog Webpage</h1>
        <h2>Blog {{number}}</h1>
        <h3>Test Blog</h1>

Make sure you note how the variable tags of the jinga2 languages are used.

Launching the Flask application Launch the server and tap the URL Wow!


On this note, we have come to the end of this tutorial class. Don't hesitate to try the above illustration. It will help you understand this course better. Enjoy your coding!

Related course: Create Web Apps with Python Flask