Poems Template

Let’s resolve that “TemplateNotFound” error, by adding a new template at templates/poems.html:

<h1>My Poems</h1>

{% for poem in poems %}
  <h2>{{ poem.id }}</h2>
  <p>{{ poem.body }}</p>
  <small>created at {{ poem.created_at }}</small>
{% endfor %}

Try It

Now visit http://localhost:5000/poems

What’s Happening in the Template

Here you’ll see some of the power of templates. We want to display the data from each poem in the database on the page. Templates allow us to run certain Python code from within our HTML.

In the following code, we can run a for loop that iterates through the list of poems. The only difference between this template code and standard Python code is that we need to tell the template we are including code, and we do that by enclosing it in {% %}, and we also need to tell the template that we are ending the for loop with the {% endfor %} line, since it can’t rely on indentation in the same way that Python code can.

We can then display each field associated with the poems database table (id, body, created_at) using dot notation (eg, poem.id, poem.body, poem.created_at).