Previous: Part 4 - Focus On Responses
In this chapter we are going to explore the basics of templates in Flask.
I have configured everything in this repo:
Download it, make sure you have Flask installed and run app.py
Curly braces
To differenciate between html and whatever you want to render, you use curly braces. In templates/curly_braces.html you'll see
<body class="container">
    {{1 + 2}}
</body>
if you go to http://127.0.0.1:5000/render-curly-braces you'll see:
That's because enclosing 1+2 in {{}} causes flask to render the expression.
Rendering a Python variable
Let's say we have a variable called message. We want to render it in the template. In the html part we do:
<body>
    {{message}}
</body>
and in app.py we pass it as a keyword argument in our return function.
@app.route('/render-variable')
def render_variable():
    return render_template('render_variable.html', message='I am a rendered variable!')
message is the templates variable name and 'I am a rendered variable!' is the value.
Going to http://127.0.0.1:5000/render-variable gives:
Rendering a loop
The syntax for a loop is as follows, python side we just render the file:
<body class="container">
    {% for i in range(5): %}
        <div>{{ i }}</div>
    {% endfor %}
</body>
Going to http://127.0.0.1:5000/render-loop gives:
Just don't forget to put rendering values in {{}}
Rendering lists
Let's say python side we have a list of fruits:
@app.route('/render-list')
def render_list():
    return render_template('render_list.html', fruits=['apple', 'orange', 'pear'])
now we have a variable called fruits available in the template. We iterate over it just like a normal list:
<body class="container">
    {% for fruit in fruits: %}
        <div>{{ fruit }}</div>
    {% endfor %}
</body>
Going to http://127.0.0.1:5000/render-list gives:
Setting a variable in the template itself.
To set a variable in the template itself you do:
{% set x = 5%}
You can then use it:
<body class="container">
    {% set x = 5%}
    <div>x is equal to {{x}}</div>
</body>
Going to http://127.0.0.1:5000/render-template-var gives:
Render ifs
It's totally possible and useful to have ifs in templates:
<body class="container">
    {% set x = 5%}
    {% if x == 5: %}
        <h2>X is equal to 5</h2>
    {% else %}
        <h2>X is not equal to 5</h2>
    {% endif %}
</body>
Going to http://127.0.0.1:5000/render-if gives:
as x is equal to 5
Where are the templates docs?
Flask actually use a sister project for templating called jinja. The whole docs can be found here: jinja.palletsprojects.com/en/2.11.x
Jinja2 is actually a very advanced and comprehensive templating library.
Throughout the chapters we'll cover the most common ones we'll use.
 
 
              






 
    
Top comments (0)