Templates in Flask

Although you can go and write HTML directly in Python, it is very cumbersome and not recommended. For example, you could do this, (but please, don’t):


Like I said, please don’t do that. It will be painful and hurtful to your poor wrists, not to mention impossible to maintain. Instead, create a folder called templates, at the same level as blog.py

dir structure flask

Create  a file called index.html under templates. Add the following code:


    <h1> Hello </h1>


Now this is pretty boring- why did we use a html file?

Jinja2 Templates

Python Flask has a cool template system, where you can put actual code in your html. We will use a simple example. Modify your code:


Some explanation:

{% %} -> This is a Jinja2 statement. Jinja2 supports the if-else condition and the for loop.

In the example above, we use {% if name %} , which means if name defined,

<h1> Hello  {{name}}</h1>

{{ }} prints the expressions into the template; in this case, name will be printed on the screen.

What’s name, you ask? That will be passed down from Python.

Modify your blog.py:

One more change. The more experienced amongst you will scream, but I’m lazy, so I’ll do it anyway. At the top, change


What I am saying is, import everything from the Flask library. Because I’m lazy and don’t want to keep typing every new function I add, that’s why.

Now goto

You will see Hello World, as before.

Now go to

This time you will see “Hello Shantnu”

Get the code: blog_templates.zip

Leave a Reply