Templating & HTML Generation

Turning data into HTML with Template, PyHTML and Jinja2.

7 lessons · 10 past questions · 33.5 marks in the papers collected here

Open the interactive lessons →Templating & HTML Generation past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Start here: why templates, from zero
  2. Python's string.Template
  3. PyHTML: HTML from nested Python calls
  4. Jinja2 expressions, loops and macros
  5. Macros and {% set %} scope
  6. Template inheritance
  7. Template folders and passing data

1. Start here: why templates, from zero

Write the page once with blanks; fill the blanks with data on every request.

what problem templates solve

The question this lesson answers. How can one page serve any amount of data without being rewritten?

A Flask view must return the HTML of a page. When the page shows data that changes (a list of students, a user's name), you could build the HTML string in Python with +, but the HTML soon disappears inside quotes and plus signs. A template turns this around: you write normal HTML with a few blanks, and the program fills them.

The same list, two ways

Built by handWith a template
Code'<ul>' + ''.join('<li>' + n + '</li>' for n in names) + '</ul>'<ul>{% for n in names %}<li>{{ n }}</li>{% endfor %}</ul>
Result for [Asha, Ravi]<ul><li>Asha</li><li>Ravi</li></ul>the same
Readable as HTMLnoyes
Escapes user textnoyes, in Flask

Three tools in this course

ToolBlanks look likeBest for
string.Template$nameshort texts, simple substitution
PyHTMLPython calls such as div(p(...))building HTML entirely in Python
Jinja2{{ name }}, {% for %}real pages: loops, conditions, layouts (Flask's choice)
Picture it

A template is a printed form with empty boxes; the context is the information you write in. The same form serves every customer. The analogy stops at loops: a Jinja2 form can grow as many rows as the data needs.

Why it works this way. The fixed parts of a page and the changing parts have different authors: you write the shape once, and the program supplies the data on each request.

Worked example: Fill one blank

Problem.

Template Hello, $name! and the context name = Ravi.

Idea.

Replace $name with its value.

  1. Template('Hello, $name!').substitute(name='Ravi').
  2. → Hello, Ravi!

Answer.

Hello, Ravi!

Common mistake.

Writing {{ name }}: that is Jinja2 syntax, not string.Template.

Worked example: Which tool wrote this?

Problem.

Three snippets: (1) {% for s in students %}, (2) $course is open, (3) ul(li('a'), li('b')).

Idea.

Each tool has its own blank syntax.

  1. (1) {% %} is Jinja2.
  2. (2) $name is string.Template.
  3. (3) nested calls are PyHTML.

Answer.

Jinja2, string.Template, PyHTML

Common mistake.

Calling (3) Jinja2 because it builds HTML.

From template to page: template with blanks + data, then blanks filled, loops run, then finished HTML, then browser shows it

How to answer

StepDo this
1Find the blanks in the template.
2Look up each name in the data passed in.
3Run loops and conditions.
4Write out everything else exactly as it is.

Worked example: Tags typed by a user

Problem.

A Flask template shows {{ name }} and name is the string <b>Ravi</b>. What does the page show?

Idea.

Flask templates escape values.

  1. The characters < and > are changed into safe codes.
  2. The browser shows them as characters.
  3. No bold element is created.

Answer.

The literal text <b>Ravi</b>.

Common mistake.

Expecting a bold name.

Check your answer in ten seconds

In a Flask page, a value becomes real HTML only if it is marked safe.

Memory line

Same shape, different data.

2. Python's string.Template

substitute insists on every value; safe_substitute leaves gaps.

$name placeholders and the two ways to fill them

The question this lesson answers. What happens to a blank for which you supplied nothing?

Fill in the blanks

The template is a sentence with labelled gaps. substitute refuses to hand it over with any gap empty; safe_substitute hands it over with the label still showing.

string.Template is the simplest template in Python's standard library. Placeholders are written $name (or ${name}). You fill them with a dictionary or keyword arguments.

from string import Template
t = Template("The $color car is near the $building.")
print(t.substitute(color="red", building="office"))
print(t.safe_substitute(color="green"))
print(t.substitute({"color": "blue", "building": "mall", "place": "Chennai"}))

Two methods

substitutesafe_substitute
missing valueraises KeyErrorleaves $name in the text
extra keysignoredignored
use whenevery value must be presentpartial filling is fine

How to answer

StepDo this
1Mark every $name, ${name} and $$.
2Turn each $$ into a single dollar sign.
3Fill the names that are supplied.
4For a missing name, decide between an error and leaving it.

Why it works this way. Two behaviours serve two needs: a strict one that refuses to produce an unfinished text, and a lenient one that leaves the blank for later.

Placeholders next to other text. A placeholder name runs as long as letters, digits and underscores continue, so $items would look for a variable called items. Write ${item}s to end the name before the s. A real dollar sign is written $$.

Placeholder syntax

WrittenMeans
$namethe value of name
${name}sthe value of name, followed by s
$$one dollar sign
Template('Cost: $$${amt} for ${item}s').substitute(amt=5, item='pen')Cost: $5 for pens

Worked example: A missing name

Problem.

Template("$lang is $desc"). What do substitute({'lang': 'Python'}) and safe_substitute({'lang': 'Python'}) give?

Idea.

Only substitute raises.

  1. desc is missing.
  2. substitute raises KeyError: 'desc'.
  3. safe_substitute returns Python is $desc.

Answer.

KeyError, then Python is $desc

Common mistake.

Thinking safe_substitute raises too.

Worked example: Template then Jinja2

Problem.

T1("... $c1 ... {{c2}} ...").substitute({'c1': 'foundation', 'c2': 'diploma'}), then the result is rendered by Jinja2 with c2='diploma'.

Idea.

string.Template only knows $name; {{c2}} is plain text to it but a placeholder to Jinja2.

  1. Step 1 replaces $c1 with foundation; {{c2}} stays as it is; the extra key c2 is ignored.
  2. Step 2: Jinja2 replaces {{c2}} with diploma.

Answer.

First the text with {{c2}} still in it, then the fully filled sentence

Common mistake.

Thinking substitute fills {{c2}} because the key c2 was passed.

Worked example: Three kinds of dollar

Problem.

What does Template("$a $b $$a ${a}b").safe_substitute(a=1) return?

Idea.

Treat each marker separately.

  1. $a becomes 1.
  2. $b has no value, so it stays.
  3. $$a becomes a dollar sign followed by the letter a.
  4. ${a}b becomes 1 followed by b.

Answer.

1 $b $a 1b

Common mistake.

Replacing the a after $$.

Check your answer in ten seconds

substitute with any missing name raises KeyError, so check the names first.

Memory line

substitute is strict; safe_substitute is forgiving.

3. PyHTML: HTML from nested Python calls

The brackets of the calls are the nesting of the tags.

how PyHTML function calls map to HTML structure

The question this lesson answers. How does a line of Python turn into nested HTML?

Nested brackets, nested tags

Each pair of brackets in the Python code is a pair of tags in the page. What is inside the brackets is inside the element.

from pyhtml import *
page = html(head(title("Quiz")), body(h2("Hi"), p("One")))
print(page.render())
PyHTML

In PyHTML each HTML element is a Python function (html, head, body, div, p, …). The positional arguments of a call are the children of that element, so the HTML tree follows the brackets of your Python code exactly.

Why it works this way. Function calls already nest inside one another, exactly as tags do, so the structure of the code can be the structure of the page.

Worked example: Where does each tag go?

Problem.

html(head(title("T")), body(div("D"), p("P"))): which tags are inside <body>?

Idea.

Read the arguments of body(...).

  1. body receives div("D") and p("P").
  2. So <div> and <p> are inside <body>; <title> is inside <head>.

Answer.

<div> and <p>

Common mistake.

Putting the div inside the head.

Worked example: Siblings, not nesting

Problem.

body(h2("H"), div("D"), p("P1"), p("P2")): are the paragraphs inside the div?

Idea.

They are separate arguments of body, so they are siblings of the div.

  1. div("D") closes after its own argument.
  2. p("P1") and p("P2") are further arguments of body.

Answer.

No: div and both p are siblings in body

Common mistake.

Reading the paragraphs as children of the div because they come after it.

Reading PyHTML like an outline. Read a PyHTML expression from the outside in, writing an opening tag each time a call starts and the matching closing tag when its brackets close. Keyword arguments become attributes and plain strings become text. If you indent each call one level deeper than its parent on paper, the HTML falls out line by line.

How to answer

StepDo this
1Find the outermost call.
2Open its tag.
3Handle the arguments from left to right.
4Close the tag when its bracket closes.

Worked example: Text between elements

Problem.

In what order does div(p("A"), "B", p("C")) show its content?

Idea.

Arguments keep their order.

  1. The first child is a paragraph with A.
  2. The second child is the plain text B.
  3. The third child is a paragraph with C.
  4. All three are inside the div.

Answer.

Paragraph A, text B, paragraph C.

Common mistake.

Putting B inside one of the paragraphs.

Check your answer in ten seconds

Count brackets: an argument belongs to the nearest call still open.

Memory line

Brackets become tags; order is kept.

4. Jinja2 expressions, loops and macros

{{ }} prints, {% %} controls, macros are reusable snippets.

{{ }}, {% for %} and macros, and how the browser shows the result

The question this lesson answers. Given a template and data, what is the exact output? Trace it as the engine does: top to bottom.

Picture it

A mail-merge letter: fixed text stays, blanks are filled, and a block repeats for every item in the list.

Jinja2 syntax

SyntaxMeaning
{{ x }}print a value
{% for i in items %} … {% endfor %}repeat for each item
{% if c %} … {% endif %}condition
{% macro f(a) %} … {% endmacro %} then {{ f(x) }}reusable snippet
{# note #}comment, not printed

index.html

{% macro show(items) %}
  {% for c in items %}
    <p>{{ c }}</p>
  {% endfor %}
{% endmacro %}
{{ show(courses) }}

Worked example: Printing a list

Problem.

{% for x in [1, 2, 3] %}{{ x }} {% endfor %}. Output?

Idea.

The body repeats per item.

  1. Item 1 → 1 .
  2. Item 2 → 2 , item 3 → 3 .

Answer.

1 2 3

Common mistake.

Expecting the list's brackets.

Worked example: A list passed straight to {{ }}

Problem.

{{ items }} with items = ["a", "b"]. What appears?

Idea.

Printing a list shows its Python representation; a loop is needed for one item per line.

  1. {{ items }} converts the list to text: ['a', 'b'].
  2. Jinja2 escapes the quotes in HTML, but the browser shows ['a', 'b'].

Answer.

['a', 'b']

Common mistake.

Expecting separate lines without a loop.

Why it works this way. {{ }} writes a value, while {% %} gives an instruction and writes nothing by itself.

Undefined values, defaults and the loop helper. In Jinja2 an undefined variable prints nothing rather than raising an error, so a misspelt name silently shows an empty gap. The default filter supplies a fallback. Inside a for loop, loop.index counts from 1, loop.first and loop.last mark the ends, and a {% else %} branch runs when the list is empty.

Rendered by Jinja2

TemplateDataOutput
[{{ missing }}]nothing[]
{{ x|default('none') }}x not givennone
{% for n in xs %}{{ loop.index }}{{ n }}{% if not loop.last %},{% endif %}{% endfor %}xs = [a, b]1a,2b
{% for n in xs %}...{% else %}empty{% endfor %}xs = []empty

Common filters

ExpressionValueOutput
name|upperashaASHA
xs|length[1, 2, 3]3
xs|join('-')[1, 2, 3]1-2-3
t|titleweb appWeb App
p|round(1)3.141593.1

Worked example: A typo in a variable name

Problem.

The view passes user="Asha"; the template says Hello {{ usr }}!.

Idea.

Undefined variables render as an empty string.

  1. usr is not defined.
  2. It prints nothing; no error is raised.

Answer.

Hello !

Common mistake.

Expecting an error page: Jinja2's default is to print nothing.

Choosing with if, elif and else. Conditions in Jinja2 read like Python but are written as tags and must be closed with {% endif %}. Inside a loop they let each row look different, such as a grade per mark.

{% for m in marks %}
  {% if m >= 90 %}A{% elif m >= 75 %}B{% else %}C{% endif %}
{% endfor %}

Macros with arguments. A macro is a template function. It can take arguments, including ones with defaults, so the same snippet renders differently each time it is called.

{% macro badge(text, kind='info') %}[{{ kind }}:{{ text }}]{% endmacro %}
{{ badge('hi') }}{{ badge('x', 'warn') }}

Worked example: Zero is not missing

Problem.

What does {{ x|default('none') }}|{{ y|default('none') }} print when x is 0 and y is not passed?

Idea.

default replaces only undefined values.

  1. x is defined, so 0 stays.
  2. y is undefined, so the default is used.

Answer.

0|none

Common mistake.

Replacing the zero as well.

Tips and tricks
  • Mark each tag as printing {{ }} or controlling {% %} before working out the output.
  • An undefined variable prints as nothing by default.
  • Count the loop passes first; that fixes how many items appear.
Memory line

Double braces print; percent braces command.

Method for any exam question

StepDo this
1Replace each expression with its value.
2Run each loop and condition.
3Apply filters from left to right.
4Copy the remaining text.

5. Macros and {% set %} scope

Variables set inside a for loop vanish after it.

what a {% set %} inside a loop leaves behind

The question this lesson answers. A variable is set inside a loop. Why is it gone afterwards?

Picture it

Notes written on a rough sheet inside a loop are thrown away when the loop ends.

Loop scope

A {% for %} loop has its own scope. {% set x = i %} inside the loop creates x only for that loop. After {% endfor %}, x is undefined, and an undefined variable renders as an empty string.

from jinja2 import Template
t = Template("{% for i in range(3) %}{% set x = i %}{% endfor %}[{{ x }}]")
print(t.render())

Why it works this way. Each loop has its own private space. A set inside it creates a name that lives only there, so the outer template never sees it.

Worked example: Set outside the loop

Problem.

{% set x = 0 %}{% for i in [1,2] %}{% set x = i %}{% endfor %}{{ x }}. Output?

Idea.

The loop's x is a new variable inside the loop; the outer x is unchanged.

  1. Outer x = 0.
  2. Inside the loop a separate x is set.
  3. After the loop the outer x is still 0.

Answer.

0

Common mistake.

Answering 2 as in Python.

Worked example: Carrying a value out with a namespace

Problem.

How can a loop update a value used after it?

Idea.

namespace objects can be changed inside loops.

  1. {% set ns = namespace(x=0) %} before the loop.
  2. Inside: {% set ns.x = i %}.
  3. After: {{ ns.x }} gives the last value, 2 for range(3).

Answer.

use namespace: output 2

Common mistake.

Expecting a plain set to work.

Escaping: why <b> shows as text. When Flask renders a template, every {{ value }} is HTML-escaped: < becomes &lt;, so text from users cannot inject tags. The |safe filter turns this off for one value; use it only for HTML you wrote yourself.

The same value, two ways

{{ s }}{{ s|safe }}
s = <b>hi</b>shows the tags as text: &lt;b&gt;hi&lt;/b&gt;shows hi in bold
Safe for user input?yesno

Where the blank lines come from. A {% ... %} tag disappears when rendered, but the newline after it stays, so templates often produce extra blank lines. A minus sign inside the tag, {%- or -%}, removes the whitespace on that side. This matters when a question asks for exact output.

The same template with and without trimming

TemplateOutput
a, then {% if true %}, b, {% endif %}, c (each on its own line)a, blank line, b, blank line, c
the same with {%- if true %} and {%- endif %}a, b, c on three lines

Worked example: A running total

Problem.

{% set total = 0 %}{% for i in [1,2] %}{% set total = total + i %}{% endfor %}{{ total }} prints what?

Idea.

A set inside a loop does not change the outer name.

  1. Inside the loop a local total is made.
  2. The outer total is never changed.

Answer.

$0$

Common mistake.

Answering 3 as Python would.

Tips and tricks
  • Ask where a variable was set. Inside a loop, it disappears after the loop.
  • To total values across passes, create ns = namespace(total=0) and update ns.total.
  • A macro produces output only when it is called.
Memory line

What is set inside a loop stays inside.

6. Template inheritance

A child fills the parent's named blocks.

{% extends %} and {% block %}

The question this lesson answers. When a child extends a base, which text comes from where?

A form with windows

The parent page is a printed form with windows cut in it. A child page may only decide what appears in the windows.

base.html and child.html

{# base.html #}
<h3>Welcome</h3>
{% block content %}{% endblock %}

{# child.html #}
{% extends "base.html" %}
{% block content %}<p>Hello</p>{% endblock %}

Correct and incorrect syntax

WrittenValid?
{% extends "base.html" %} + {% block abc %}yes
{% block %} (no name)no: a block needs a name
{% link template "base.html" %}no: not a Jinja2 tag
{% block "base.html" %}no: blocks take a name, not a file

Why it works this way. Pages of one site share a frame. Writing it once and letting each page fill named holes means a change to the frame happens in one place.

Worked example: Filling a block

Problem.

layout.html has {% block body %}{% endblock %}. Child 1 fills {% block main %}Hi{% endblock %}; child 2 fills {% block body %}Hi{% endblock %}. Both extend the layout.

Idea.

A child block replaces the parent block with the same name.

  1. Child 1 names a block the parent does not have, so its text has no place and the page shows only the layout.
  2. Child 2 matches body, so Hi appears there.

Answer.

Only child 2

Common mistake.

Expecting an error for the wrong name; the text is silently left out.

Worked example: A misnamed block

Problem.

The child fills {% block xyz %} but the parent has only abc. What happens?

Idea.

A child block with no matching parent block is never shown.

  1. The parent renders its own abc (empty).
  2. The child's xyz has nowhere to go.

Answer.

the child's content does not appear

Common mistake.

Expecting it to be appended.

Keeping the parent's text and pasting pieces. Inside a child's block, {{ super() }} inserts the parent's content for that block, so the child can add to it instead of replacing it. {% include 'foot.html' %} pastes another template in place, which suits pieces such as a footer used on many pages.

{# base.html #}
<h1>{% block title %}Site{% endblock %}</h1>{% include 'foot.html' %}

{# page.html #}
{% extends 'base.html' %}
{% block title %}Page - {{ super() }}{% endblock %}

Worked example: Replace or extend?

Problem.

Same base. The child's block is {% block title %}Page{% endblock %} (no super).

Idea.

Without super(), the child replaces the block.

  1. The child's block replaces Site.
  2. Heading: Page.

Answer.

<h1>Page</h1>

Common mistake.

Expecting Page Site: the parent text appears only with super().

How inheritance builds a page: child says: extends the base, then start from the base page, then child blocks replace base blocks, then final HTML

How to answer

StepDo this
1Start from the parent page.
2For each block, use the child's version if there is one.
3Otherwise keep the parent's content.
4Ignore child text outside every block.

Worked example: Adding without replacing

Problem.

The parent has {% block t %}Site{% endblock %}. The child has the line Hello outside blocks and {% block t %}{{ super() }} - Home{% endblock %}. Output of the block, and is Hello shown?

Idea.

super() brings in the parent's content.

  1. The child replaces block t.
  2. super() inserts Site.
  3. The block becomes Site - Home.
  4. Hello is outside every block, so it is dropped.

Answer.

Site - Home; Hello is not shown.

Common mistake.

Showing Hello at the top of the page.

Check your answer in ten seconds

In a child template, only what is inside a block can appear.

Memory line

The base gives the frame; the child fills named blocks.

7. Template folders and passing data

Flask searches one template folder; keyword arguments become template variables.

where Flask looks for templates and how data reaches them

The question this lesson answers. Where does Flask look for a template, and how do your values reach it?

Picture it

A kitchen where recipes are always kept in one drawer: the cook looks there without being told.

Template folder

render_template("x.html") searches only the app's template folder: templates/ next to the app by default, or the folder given by Flask(__name__, template_folder="..."). Paths such as "public/home.html" are relative to that folder. A file anywhere else raises TemplateNotFound (a 500 error).

app = Flask(__name__, template_folder="my_templates")

@app.route("/")
def home():
    return render_template("public/home.html")

@app.route("/page")
def page():
    return render_template("page.html")

URL data into a template

@app.route("/card/<int:width>/<theme>")
def card(width, theme):
    box = {"width": str(width) + "px", "theme": theme}
    return render_template("card.html", box=box)

Worked example: Which URL works?

Problem.

Using card above, which address gives a dark card 300 pixels wide: /card/dark/300 or /card/300/dark?

Idea.

The rule's order is width, then theme, and width must be an integer.

  1. /card/dark/300: dark is not an int, so 404.
  2. /card/300/dark matches.

Answer.

/card/300/dark

Common mistake.

Using query parameters, which this rule does not read.

Worked example: Two folders

Problem.

With template_folder="pages": which call works, render_template("admin/report.html") (file in pages/admin/) or render_template("home.html") (file only in templates/)?

Idea.

Only the configured folder and its subfolders are searched.

  1. pages/admin/report.html exists, so it renders.
  2. templates/ is no longer searched, so home.html raises TemplateNotFound.

Answer.

The admin report renders; home.html fails

Common mistake.

Thinking Flask still searches templates/ as a backup.

Why it works this way. A fixed folder lets a view name a page without knowing where the program was started from.

From view to page, step by step. render_template('page.html', user=u) finds templates/page.html, follows any extends and includes, fills every {{ }} from the keyword arguments (escaping HTML), runs the loops and conditions, and returns one finished HTML string, which the view returns as the response.

What goes wrong and what you see

MistakeResult
template not in templates/TemplateNotFound, a 500
variable not passedprints nothing (no error)
HTML passed in a variableshown as text unless marked safe

A complete Flask page, start to finish. In practice the pieces come together like this: the view gathers data, calls render_template with that data, the template extends a base layout, loops over the data and escapes each value, and the finished HTML is the response.

@app.route("/students")
def students():
    rows = [{"name": "Asha", "mark": 92}, {"name": "Ravi", "mark": 70}]
    return render_template("students.html", rows=rows, title="Class list")
{% extends "base.html" %}
{% block content %}
<h2>{{ title }}</h2>
<ul>{% for r in rows %}<li>{{ r.name }}: {{ r.mark }}</li>{% endfor %}</ul>
{% endblock %}

render_template step by step: view calls render_template, then file found in the template folder, then named values filled in, then HTML string returned

How to answer

StepDo this
1Find the template folder of the app.
2Join it with the path given to render_template.
3Check the names of the keyword arguments.
4Use those names inside the template.

Worked example: A name that was never passed

Problem.

A view passes items=[1, 2], but the template loops with {% for r in rows %}<li>{{ r }}</li>{% endfor %}. What is shown?

Idea.

An unknown name is empty in a default Jinja2 setup.

  1. rows was never passed.
  2. Looping over an undefined name runs zero times.
  3. No error is raised.
  4. No list item is produced.

Answer.

Nothing from the loop.

Common mistake.

Expecting the items 1 and 2, or an error.

Check your answer in ten seconds

When a page is mysteriously empty, compare the names in the view with the names in the template.

Memory line

Templates live in the template folder; values travel by name.

Practise this topic →

Weeks covering this topic

Other MAD 1 topics