The Analogy: The Print Shop's Mail-Merge and Proofing Station
A commercial print shop runs a mail-merge operation. It keeps a master form letter -- a printed template with blank fields where a name, a balance, or an appointment date will go. The shop never retypes the letter for each of ten thousand recipients; it feeds the master and a data list into the merge machine, which stamps each recipient's details into the blanks and runs off a personalised copy. The master letter with its blanks is your template, the recipient data list is the context you hand the renderer, and the finished personalised letters are the rendered HTML that goes back to the browser.
The shop has one ironclad rule, learned the hard way: any text that comes from outside -- a customer-supplied message, a name typed into a web form -- passes through a proofing station before it ever touches a printing plate. The proofing clerk's entire job is to neutralise anything in that text that could be mistaken for a typesetting instruction, so a stray plate-command sequence prints as visible ink rather than being obeyed by the press. This is autoescaping: by default the merge treats every value as inert text to display, converting characters like the angle brackets and ampersand into their harmless printable forms so they appear as themselves instead of being interpreted as markup.
The shop also keeps house stationery -- a letterhead, a footer with the return address and the legal boilerplate, a standard margin. Every letter is printed onto that stationery, and the merge fills only the body block that each specific letter overrides. Change the letterhead once and every letter produced afterward carries it, without editing a single body. This is template inheritance: a base layout defines the frame and a set of named blocks, and each page extends the base and fills only the blocks it cares about, so a site-wide change happens in one file.
The failure arrives with a clerk under deadline who decides the proofing station is slowing down one "trusted" batch and routes a customer's raw message straight onto the plate. It prints fine for every ordinary message. Then one customer's message field holds not a greeting but a real plate-command sequence, and because it skipped proofing the press obeys it: the run is corrupted, and an attacker who discovered the shortcut can now make the shop's own press act on their behalf. Marking a value as pre-approved to bypass proofing is exactly the | safe filter, and reaching for it on anything a user supplied is how a template quietly becomes a cross-site-scripting hole.
Syntax or Core Structure
A template keeps your HTML out of your Python. Flask ships with the Jinja2 engine, so you write a template full of placeholders and hand it a context -- a set of values -- and Jinja renders the finished text. In a real project the template lives in a file under templates/ and you call render_template("page.html", ...); to keep every example on this page runnable and self-contained, we use render_template_string, which renders a template given as a string and behaves identically in every way that matters here. Two delimiters do almost all the work: {{ ... }} prints the value of an expression, and {% ... %} runs a statement such as a loop or an if.
from flask import Flask, render_template_string
app = Flask(__name__)
TEMPLATE = "Hello, {{ name }}! You have {{ count }} unread messages."
with app.app_context():
html = render_template_string(TEMPLATE, name="Ada", count=3)
print(html)
Output:
Hello, Ada! You have 3 unread messages.
The keyword arguments (name="Ada", count=3) become the template's context: each {{ name }} is replaced by the matching value, and count, an integer, is rendered as its printed form. Rendering happens inside app.app_context() here only because we are calling the renderer outside a request; inside a normal view function the application context already exists, so you just return render_template(...). The template itself contains no Python logic beyond the substitutions -- that separation is the entire point.
Technical Depth: Autoescaping, Control Flow, and Inheritance
Jinja does far more than fill blanks. It has filters that transform values, control structures for loops and conditionals, and an inheritance system for sharing layout -- and, most importantly for a web app, it escapes output by default so that data can never be mistaken for markup. Filters are applied with a pipe and chained left to right; here are the ones you will reach for constantly.
| Filter | What it does | Example |
|---|---|---|
default | Falls back when the value is missing or undefined | missing name renders guest |
length | Counts items in a sequence or string | a 3-item list renders 3 |
upper / lower | Changes case | ada renders ADA |
format | printf-style number and string formatting | 1.5 renders 1.50 |
join | Joins a list into one string with a separator | two tags render a, b |
tojson | Serialises a value to JSON, safe inside a script block | a dict renders {} |
safe | Marks a value already-safe so it is NOT escaped | escaping turned off |
e / escape | Forces escaping even where autoescape is off | angle brackets render as entities |
Autoescaping and the safe filter
This is the single most important behaviour to understand. In an HTML template, Jinja escapes every printed value by default: characters that mean something in HTML are converted to entities so the browser shows them literally instead of acting on them.
from flask import Flask, render_template_string
app = Flask(__name__)
with app.app_context():
evil = "<b>hi</b>"
print("auto:", render_template_string("{{ v }}", v=evil))
print("safe:", render_template_string("{{ v | safe }}", v=evil))
Output:
auto: <b>hi</b>
safe: <b>hi</b>
With autoescaping, <b>hi</b> becomes <b>hi</b> -- the browser renders the literal text, not bold. The safe filter switches escaping off for that value, emitting the raw tags. That is exactly what you want for markup you generated and trust, and exactly what you must never do to a value that came from a user, because it hands them the ability to inject their own HTML and script.
Loops, conditionals, and filters
Templates iterate and branch with {% for %} and {% if %}. Inside a loop, Jinja hands you a loop helper -- loop.index (1-based), loop.index0, loop.first, loop.last -- so you rarely need to track counters yourself. Filters format the values as you print them.
from flask import Flask, render_template_string
app = Flask(__name__)
TMPL = """{% for item in items %}{{ loop.index }}. {{ item.name }} - {{ "%.2f"|format(item.price) }}
{% endfor %}"""
with app.app_context():
items = [{"name": "Pen", "price": 1.5}, {"name": "Notebook", "price": 12.0}]
print(render_template_string(TMPL, items=items), end="")
Output:
1. Pen - 1.50
2. Notebook - 12.00
loop.index numbers the rows from one, and "%.2f"|format(item.price) pins each price to two decimals so 1.5 prints as 1.50. Filters chain: you could write item.name|upper|truncate(20) to uppercase then shorten. Keep the logic this light -- a template should format data, never compute it.
Layouts with template inheritance
Real sites share a frame -- the same header, nav, and footer on every page. Inheritance lets one base template own that frame and expose named blocks that child pages fill. A base template under templates/base.html looks like this:
<!doctype html>
<title>{% block title %}ACME{% endblock %}</title>
<header>ACME Store</header>
<main>{% block content %}{% endblock %}</main>
<footer>(c) ACME</footer>
A page template extends it and overrides only the blocks it needs, inheriting everything else:
{% extends "base.html" %}
{% block title %}Products{% endblock %}
{% block content %}
<h1>Our products</h1>
<p>{{ products | length }} in stock</p>
{% endblock %}
Rendering render_template("products.html", products=rows) produces the full page: the child's blocks slotted into the base's frame. Override a block completely, or call {{ super() }} inside it to keep the parent's content and add to it. For smaller reusable fragments -- a product card, a flash-message banner -- {% include "partials/card.html" %} pulls another template in. Change base.html once and every page that extends it updates, which is the whole reason the pattern exists.
Real World Example: A Guestbook That Trusts Its Comments
A team ships a guestbook: visitors leave a comment, it is stored, and every visitor sees the list. They used inheritance for the page frame. During review, someone noticed that a commenter's <b>bold</b> showed up as literal text instead of bold, and "fixed" it by marking the comment | safe so the formatting would render. The program below reproduces that exact page in-process, using an in-memory list in place of the database and a DictLoader in place of a templates/ folder so it runs standalone.
from flask import Flask, render_template
from jinja2 import DictLoader
app = Flask(__name__)
app.jinja_loader = DictLoader({
"layout.html": "PAGE: {{ title }}\n{% block content %}{% endblock %}",
"guestbook.html": (
"{% extends 'layout.html' %}"
"{% block content %}"
"{% for c in comments %}- {{ c | safe }}\n{% endfor %}"
"{% endblock %}"
),
})
comments = ["nice site", "<script>steal(document.cookie)</script>"]
with app.test_request_context():
page = render_template("guestbook.html", title="Guestbook", comments=comments)
print(page, end="")
Output:
PAGE: Guestbook
- nice site
- <script>steal(document.cookie)</script>
Trace it. The base layout.html prints PAGE: Guestbook and a newline, then yields to the child's content block. The child loops over the two stored comments and prints each behind a dash. The first, nice site, is ordinary text. The second is not a comment at all -- it is a <script> tag -- and because it is rendered through | safe, Jinja emits it verbatim into the page instead of escaping it.
That raw <script>steal(document.cookie)</script> is now part of the HTML every visitor downloads, so every visitor's browser runs it and ships their session cookie to the attacker. This is stored (persistent) cross-site scripting: the payload was submitted once, saved like any other comment, and then executes in the browser of everyone who views the page afterward -- no further action from the attacker required. Had autoescaping been left on, that same comment would have rendered as the harmless visible text <script>steal(document.cookie)</script>, exactly as the print-shop proofing station intended.
The genuine design flaw is applying | safe to attacker-controllable input, which switches off the one defence standing between stored data and the DOM. The wish for "a little formatting" never justifies trusting arbitrary HTML from strangers. The fix is to keep autoescaping on and never mark user input safe; if limited formatting is a real requirement, sanitise the value server-side against a strict allowlist (a library such as nh3/bleach that strips <script>, inline event handlers, and javascript: URLs), and only then treat the sanitised, known-safe result as safe -- or render a constrained Markdown subset. The rule is simple: escape by default, sanitise deliberately, and reserve | safe for markup you generated yourself.
Common Mistakes
- Marking user input
| safe. This is the Real World flaw. Applyingsafe(or wrapping a value inMarkup(...)) to anything a user supplied disables escaping and opens a cross-site-scripting hole. Reservesafefor markup your own code produced and trusts.
- Assuming autoescaping is always on. Escaping is keyed off the template's name: Flask escapes
.html,.htm,.xml, and.xhtml, but a template namedreport.txtis not escaped, and an{% autoescape false %}block turns it off locally. Do not assume every rendered value is safe -- know which templates escape.
- Believing HTML-escaping covers every context. Autoescaping protects HTML body text, not a value dropped into a
<script>block, an inline event handler, or ahref. Serialise data for JavaScript with| tojson, and validate or allowlist URLs -- ajavascript:URL sails past HTML-escaping untouched.
- Putting business logic in templates. A template should format data, not fetch or compute it. Querying the database, calling services, or running non-trivial calculations inside
{{ }}scatters logic into markup where it cannot be tested and often runs once per loop iteration.
- Assembling HTML by string concatenation in Python. Building markup with f-strings or
+in a view ("<li>" + name + "</li>") bypasses Jinja's escaping entirely and reintroduces the injection you were protected from. Render a template instead and let the engine escape.
- Copy-pasting layout across pages. Repeating the header, nav, and footer in every template means a change touches every file and drifts out of sync. Define one base template and
{% extends %}it; pull shared fragments in with{% include %}.
- Letting undefined variables render silently. By default Jinja prints a missing variable as an empty string, so a typo like
{{ usr.name }}produces blank output instead of an error and hides the bug. Use thedefaultfilter for genuine optionals, and considerStrictUndefinedin development to surface mistakes.
- Doing expensive work inside a template loop. Calling a property that hits the database or a service from within
{% for %}turns one page into dozens of queries. Gather all the data in the view, pass a ready list to the template, and let the loop only format it.
- Misplacing templates or overusing
render_template_string.render_templatelooks under the app'stemplates/folder; a file elsewhere raisesTemplateNotFound. Andrender_template_stringon a value that itself contains user input invites server-side template injection -- keep templates in files and pass user data only as context.
Best Practices
- Keep autoescaping on and never mark user input safe. Treat escaping as a non-negotiable default. The moment you reach for
| safeorMarkup, ask whether the value could contain anything a user typed; if it could, do not.
- Keep templates in files and share layout through inheritance. Put templates under
templates/and render them withrender_template. Define one base layout, extend it per page, and factor repeated fragments into includes so a design change happens in one place.
- Pass ready-to-display data from the view. Do the querying, computing, and shaping in Python, then hand the template a clean context. A template that only formats is easy to read, cheap to render, and impossible to fill with hidden logic.
- Escape for the destination context. HTML body text is handled for you, but serialise data bound for JavaScript with
| tojson, keep attribute values quoted, and validate any URL before printing it. Different contexts need different encoding.
- Sanitise, do not trust, when user formatting is required. If comments or posts must allow some HTML, run them through an allowlist sanitiser (
nh3/bleach) or render a constrained Markdown subset, and mark only that vetted output safe.
- Factor repeated markup into macros and filters. A
{% macro %}for a product card or form field, and custom filters for domain formatting, keep templates DRY and consistent without pushing logic back into the markup.
- Add a Content-Security-Policy as defence in depth. Even with escaping, a CSP that forbids inline script means a single missed injection cannot execute, turning a would-be breach into a blocked resource.
- Fail loudly on undefined variables in development. Render with
StrictUndefinedlocally so typos raise instead of silently producing blank output, and use thedefaultfilter to mark the values that are genuinely optional.
Practice Exercises
- Watch escaping work. Render a single comment whose text is
<script>alert(1)</script>throughrender_template_string("{{ c }}", c=comment)with autoescaping on, and confirm the output is the escaped<script>alert(1)</script>. Then explain, in one sentence, why adding| safe-- as the guestbook did -- turns that same input into a working attack.
- Build a layout with inheritance. Using a
DictLoader, define abase.htmlwith atitleblock and acontentblock wrapped in a header and footer, and apage.htmlthat extends it and overrides both. Renderpage.htmland confirm the output shows the base's frame around the child's content.
- Format a product list. Write a template that loops over a list of product dicts and prints, per row,
loop.index, the name in upper case, and the price formatted to two decimals. For any product missing adescription, use thedefaultfilter to printno description.
- Escape for JavaScript. Pass a dict such as
{"name": "Ada", "role": "admin"}to a template that embeds it inside a<script>block asconst user = {{ user | tojson }};. Compare the output with a version that uses{{ user }}alone, and explain why the JavaScript context requirestojsonrather than plain HTML-escaping.