Turning data into HTML with Template, PyHTML and Jinja2.
Open the interactive lessons →Templating & HTML Generation past questions
Contents
- Start here: why templates, from zero
- Python's string.Template
- PyHTML: HTML from nested Python calls
- Jinja2 expressions, loops and macros
- Macros and {% set %} scope
- Template inheritance
- 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 hand | With 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 HTML | no | yes |
| Escapes user text | no | yes, in Flask |
Three tools in this course
| Tool | Blanks look like | Best for |
|---|---|---|
string.Template | $name | short texts, simple substitution |
| PyHTML | Python calls such as div(p(...)) | building HTML entirely in Python |
| Jinja2 | {{ name }}, {% for %} | real pages: loops, conditions, layouts (Flask's choice) |
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.
Template('Hello, $name!').substitute(name='Ravi').- → 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) {% %} is Jinja2.
- (2)
$nameis string.Template. - (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
| Step | Do this |
|---|---|
| 1 | Find the blanks in the template. |
| 2 | Look up each name in the data passed in. |
| 3 | Run loops and conditions. |
| 4 | Write 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.
- The characters
<and>are changed into safe codes. - The browser shows them as characters.
- No bold element is created.
Answer.
The literal text <b>Ravi</b>.
Common mistake.
Expecting a bold name.
In a Flask page, a value becomes real HTML only if it is marked safe.
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?
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
substitute | safe_substitute | |
|---|---|---|
| missing value | raises KeyError | leaves $name in the text |
| extra keys | ignored | ignored |
| use when | every value must be present | partial filling is fine |
How to answer
| Step | Do this |
|---|---|
| 1 | Mark every $name, ${name} and $$. |
| 2 | Turn each $$ into a single dollar sign. |
| 3 | Fill the names that are supplied. |
| 4 | For 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
| Written | Means |
|---|---|
$name | the value of name |
${name}s | the 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.
descis missing.substituteraisesKeyError: 'desc'.safe_substitutereturnsPython 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.
- Step 1 replaces
$c1withfoundation;{{c2}}stays as it is; the extra keyc2is ignored. - Step 2: Jinja2 replaces
{{c2}}withdiploma.
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.
$abecomes 1.$bhas no value, so it stays.$$abecomes a dollar sign followed by the letter a.${a}bbecomes 1 followed by b.
Answer.
1 $b $a 1b
Common mistake.
Replacing the a after $$.
substitute with any missing name raises KeyError, so check the names first.
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?
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())
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(...).
bodyreceivesdiv("D")andp("P").- 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.
div("D")closes after its own argument.p("P1")andp("P2")are further arguments ofbody.
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
| Step | Do this |
|---|---|
| 1 | Find the outermost call. |
| 2 | Open its tag. |
| 3 | Handle the arguments from left to right. |
| 4 | Close 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.
- The first child is a paragraph with A.
- The second child is the plain text B.
- The third child is a paragraph with C.
- All three are inside the
div.
Answer.
Paragraph A, text B, paragraph C.
Common mistake.
Putting B inside one of the paragraphs.
Count brackets: an argument belongs to the nearest call still open.
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.
A mail-merge letter: fixed text stays, blanks are filled, and a block repeats for every item in the list.
Jinja2 syntax
| Syntax | Meaning |
|---|---|
{{ 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.
- Item 1 →
1. - 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.
{{ items }}converts the list to text:['a', 'b'].- 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
| Template | Data | Output |
|---|---|---|
[{{ missing }}] | nothing | [] |
{{ x|default('none') }} | x not given | none |
{% 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
| Expression | Value | Output |
|---|---|---|
name|upper | asha | ASHA |
xs|length | [1, 2, 3] | 3 |
xs|join('-') | [1, 2, 3] | 1-2-3 |
t|title | web app | Web App |
p|round(1) | 3.14159 | 3.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.
- usr is not defined.
- 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.
xis defined, so 0 stays.yis undefined, so the default is used.
Answer.
0|none
Common mistake.
Replacing the zero as well.
- 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.
Double braces print; percent braces command.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Replace each expression with its value. |
| 2 | Run each loop and condition. |
| 3 | Apply filters from left to right. |
| 4 | Copy 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?
Notes written on a rough sheet inside a loop are thrown away when the loop ends.
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.
- Outer
x = 0. - Inside the loop a separate
xis set. - After the loop the outer
xis 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.
{% set ns = namespace(x=0) %}before the loop.- Inside:
{% set ns.x = i %}. - After:
{{ ns.x }}gives the last value, 2 forrange(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 <, 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: <b>hi</b> | shows hi in bold |
| Safe for user input? | yes | no |
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
| Template | Output |
|---|---|
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.
- Inside the loop a local
totalis made. - The outer
totalis never changed.
Answer.
$0$
Common mistake.
Answering 3 as Python would.
- 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 updatens.total. - A macro produces output only when it is called.
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?
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
| Written | Valid? |
|---|---|
{% 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.
- Child 1 names a block the parent does not have, so its text has no place and the page shows only the layout.
- Child 2 matches
body, soHiappears 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.
- The parent renders its own
abc(empty). - The child's
xyzhas 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.
- The child's block replaces Site.
- 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
| Step | Do this |
|---|---|
| 1 | Start from the parent page. |
| 2 | For each block, use the child's version if there is one. |
| 3 | Otherwise keep the parent's content. |
| 4 | Ignore 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.
- The child replaces block
t. super()insertsSite.- The block becomes
Site - Home. Hellois outside every block, so it is dropped.
Answer.
Site - Home; Hello is not shown.
Common mistake.
Showing Hello at the top of the page.
In a child template, only what is inside a block can appear.
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?
A kitchen where recipes are always kept in one drawer: the cook looks there without being told.
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.
/card/dark/300:darkis not an int, so 404./card/300/darkmatches.
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.
pages/admin/report.htmlexists, so it renders.templates/is no longer searched, sohome.htmlraises 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
| Mistake | Result |
|---|---|
| template not in templates/ | TemplateNotFound, a 500 |
| variable not passed | prints nothing (no error) |
| HTML passed in a variable | shown 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
| Step | Do this |
|---|---|
| 1 | Find the template folder of the app. |
| 2 | Join it with the path given to render_template. |
| 3 | Check the names of the keyword arguments. |
| 4 | Use 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.
rowswas never passed.- Looping over an undefined name runs zero times.
- No error is raised.
- No list item is produced.
Answer.
Nothing from the loop.
Common mistake.
Expecting the items 1 and 2, or an error.
When a page is mysteriously empty, compare the names in the view with the names in the template.
Templates live in the template folder; values travel by name.