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:

 <html>

    <h1> Hello </h1>

 </html>

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

to

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 http://127.0.0.1:5000/

You will see Hello World, as before.

Now go to http://127.0.0.1:5000/shantnu

This time you will see “Hello Shantnu”

Get the code: blog_templates.zip

3 thoughts on “Templates in Flask”

  1. All your html code is screwed up by the parser of your site. It looks like you’ve made very helpfull tutorial, but It’s hard to follow it with this ugly html examples. Please do something about it.

    1. Oh boy. It’s “sanitised” everything!

      I haven’t looked at this code for years, and I didn’t even think anyone read it. Let me try to fix it 🙂

    2. okay, I’ve turned off sanitisation, but it has to be done for each block separately. If you find any more problems, moan about it and I’ll fix it 🙂

Leave a Reply