Overview
Flask uses Jinja2 as its template engine, providing powerful template rendering with automatic escaping, inheritance, and integration with Flask’s context system.Template Basics
Directory Structure
By default, Flask looks for templates in thetemplates folder:
Rendering Templates
Fromtemplating.py:136-161, use render_template() to render templates:
Jinja2 Environment
Flask creates a customized Jinja2 environment (fromapp.py:469-507):
Template Context
Automatic Variables
Fromtemplating.py:21-33, Flask automatically injects these variables:
Passing Variables
Pass data to templates:Template Syntax
Variables
Control Structures
Conditionals
Loops
Filters
Transform variables:Template Inheritance
Base template (base.html):
Template Inclusion
Include reusable components:Macros
Create reusable template functions:Custom Template Context
Context Processors
Fromapp.py:590-618, add variables to all templates:
Custom Filters
Register custom Jinja2 filters:Custom Tests
Create custom template tests:Global Functions
Add custom global functions:Rendering from Strings
Fromtemplating.py:151-160, render template strings:
Streaming Templates
Fromtemplating.py:181-212, stream large templates:
Auto-escaping
Flask automatically escapes HTML:Blueprint Templates
Blueprints can have their own template folders:templating.py:49-121, Flask’s DispatchingJinjaLoader searches:
- Blueprint template folders
- Application template folder
Template Loading
Custom Loader
Customize template loading:Debug Template Loading
Enable template loading explanation:Best Practices
Template Inheritance
Use base templates to avoid repetition
Security First
Never disable auto-escaping unless absolutely necessary
Separation of Concerns
Keep logic in Python, presentation in templates
Reusable Components
Use macros and includes for common components
Related Concepts
- Application - Flask application configuration
- Request and Response - Working with requests
- Application Context - Template context variables
