Overview
FastAPI supports rendering HTML templates using Jinja2, a powerful and widely-used templating engine. This is useful when you need to return HTML pages instead of JSON responses, such as building admin interfaces, documentation pages, or server-side rendered applications.Installation
First, install Jinja2 and the additional dependencies for serving static files:Jinja2 is the same template engine used by Flask, so if you’re familiar with Flask templates, you’ll feel right at home.
Basic Setup
Here’s a complete example showing how to set up Jinja2 templates with FastAPI:Project Structure
Your project should have the following structure:Creating Templates
Basic Template
Create a filetemplates/item.html:
Template Context
Pass data to your templates using thecontext parameter:
Advanced Template Features
Template Inheritance
Create a base templatetemplates/base.html:
templates/page.html:
Conditional Rendering
Loops
Jinja2 supports many Python-like features including filters, macros, and includes. Check the Jinja2 documentation for the complete feature set.
Custom Filters
Add custom Jinja2 filters to your templates:Serving Static Files
Static files like CSS, JavaScript, and images should be served from a dedicated directory:Error Pages
Create custom error pages:Best Practices
Escape User Input
Jinja2 auto-escapes HTML by default, but be careful when using
|safe filter or {% autoescape false %}.Organize Templates
Use subdirectories for different sections:
templates/admin/, templates/public/, etc.Cache Templates
In production, templates are automatically cached. Set
auto_reload=False for better performance.Separate Concerns
Keep business logic in Python and presentation logic in templates.
Performance Considerations
Testing Templates
Test your template endpoints using FastAPI’s test client:Related Topics
- Learn about Static Files for serving CSS, JS, and images
- Explore Custom Responses for other response types
- Check out Server-Side Events for real-time updates