Templates

One limitation of using plain HTML is that it won’t allow us to embed data from our application code in it easily, but luckily Flask gives us templates that make it easier to do this. Templates allow us to print the values of Python variables in our HTML files, and allow us to run some Python code in them such as loops. This is how our applications can become more dynamic.

Templates also allow us to reuse small snippets of HTML rather than creating full HTML files for each part of our application. For example, if you had the same header on every page, you could write the HTML for the header once, and then include it in other pages. That way you’ll only need to change it one place, rather than on every page of your application. You’ll see some examples of the power of templates as we go through the next parts of the workshop.

Here’s our first template which we will place in templates/poem.html:

<h1>Poem</h1>
<p>{{ poem }}</p>

<small>Refresh the page to get a new poem</small>

Create the Template File

  1. First open the file explorer side panel.

explorer

  1. Hover over “JUMPSTART-WEBDEV” which exposes some buttons. Hover over the new file icon and click it.

hover over new file

  1. Enter both the directory name, a slash, and then the filename poem.html. So you’ll enter templates/poem.html: enter directory name and filename

  2. When you hit enter you should see a new file poem.html within the templates directory. saved file

  3. Enter the following code in the editor for poem.html and save it.

<h1>Poem</h1>
<p>{{ poem }}</p>

<small>Refresh the page to get a new poem</small>

Using the Template

And instead of just showing the poem as plain text, we will update our /poem route in app.py to use this template in our route:

We will replace:

    return poem

With this code to render our template:

    return render_template('poem.html', poem=poem)

If you paste this in, check that you have the leading whitespace correct. Whitespace for indentation matters in Python.

Try it out at: http://localhost:5000/poem

What’s Happening?

Note how we pass in the variable poem to our templates. If you look at the template again you’ll see that the template includes some markup like {{ poem }} which is used to substitute in the value of the variable.

Different frameworks may use a different syntax for how to replace variables in templates.

Here’s what our full Flask application looks like now:

# app.py

from flask import Flask, render_template, redirect, url_for, jsonify
import poembot

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello world!"

@app.route('/poem')
def poem():
    poem = poembot.generate_poem()
    return render_template('poem.html', poem=poem)

if __name__ == '__main__':
    app.run(debug=True)

And here are all of the files we will have in our file explorer with our new template file:

file explorer with template file