Templates
Flask uses Jinja2 as its template engine for generating HTML. Templates separate page structure from Python logic, and variables are HTML-escaped by default, providing built-in XSS protection.
Basic Usage
render_template looks up templates in the application's (or blueprint's) templates/ directory; keyword arguments become template variables.
Template Syntax
The loop object exposes loop state such as index (1-based), first, and last.
Template Inheritance
Define the skeleton in a base template; child templates fill in only what differs:
Reusable Fragments: include and Macros
Objects Available in Every Template
Flask injects these automatically: request, session, g, url_for(), get_flashed_messages(), config.
Custom Filters and Globals
Escaping and Safety
- Variables are escaped by default; output trusted HTML with
{{ content|safe }}— but never apply safe to user input. - On the Python side,
markupsafe.Markupmarks a string as safe.
Static files (CSS/JS/images) are covered in the next chapter.