Flask Templates
Templates make it easy to write valid HTML. Flask supports my favourite template engine, Jinja2.
Prerequisites: Hello Flask - Write a Python Web App and Linux command line and administration.
Always start from Hello world. Once that's working, we can add HTML templates.
Directory Structure # ↑
Directory structure is pretty simple. HTML templates to to templates/ folder.
$
.
├── templates/
│ └── base.html
└── templates-flask.py
Templates-flask.py # ↑
Our app has just two new lines compared to "hello world".
#!/usr/bin/python3
=
return
Let's have a look at those new lines
We must import what we use. Render template is imported to main namespace, so we can call it just "render_template()" instead of "flask.render_template".
return
In "hello world", we just returned a string 'return "Hello"'. Writing a whole HTML5 page like that would be tedious. Here, we have the HTML template in a separate file.
We declare a new variable called "greeting" for use in the template.
templates/base.html # ↑
By default, templates go to templates/ folder.
/2020/flask-templates/02-templates/templates/base.html
Hello Templates
{{ greeting }}
Learn Flask templates at
TeroKarvinen.com.
It's just plain HTML, except for the variables.
<h1>{{ greeting }}</h1>
Variables are marked with curly brackets, also known as handlebars, mustache, curly braces (fi: aaltosulkeet). This {{ greeting }} is replaced with the value of the greeting, in this case "Hello Variables!".
Let's Run # ↑
$
Browse to http://localhost:5000.
That's it. You're now using templates.
What Next? More Template Tricks # ↑
Flask uses my favourite template engine, Jinja2. It has support for a couple of more useful things, which you can learn from Jinja2 documenation.
- Template inheritage. Most of my templates are short, as they inherit the HTML5 boilerplate from base.html. {% extends "base.html" %} {% block content %} Hello {% endblock %}
- Control structures: {% for book in books %} {{ book }} {{ endfor }}
- Filters: {{ message.body|truncate(160) }}
Adminstrivia # ↑
This page has been updated.
