Jinja2
Fast and expressive template engine for Python with autoescaping, filters, and template inheritance.
Official Documentation ↗v3. Check the official docs for the latest API surface.Installation
pip install jinja2Methods
No methods match this filter.
Fast and expressive template engine for Python with autoescaping, filters, and template inheritance.
Overview
Jinja2 compiles templates into Python code and renders them with a dict-like context. Its syntax covers interpolation with filters, control flow, macros, and template inheritance, which together keep markup maintainable.
The Environment centralizes configuration: loaders locate templates, autoescape secures HTML output, and custom filters and tests extend the vocabulary safely. The same engine powers HTML pages, configuration files, and reports, with sandboxing available for untrusted designers.
Core Methods
The most frequently used entry points, with signatures and runnable examples:
Environment— Holds configuration and loads templates; autoescape must be on when rendering HTML.get_template / from_string— Renders a named template from the loader or an inline source string with keyword context.custom filters— Registers Python functions usable in templates through the pipe syntax for domain formatting.template inheritance— Shared layout blocks that child templates override, keeping chrome and pages separate.
Usage Notes
- Create one Environment at startup with the right loader and autoescape; per-render environments waste compilation.
- Enable StrictUndefined in development to surface missing context keys immediately.
- Keep logic in filters and Python code, templates stay readable when they mostly present data.
Common Pitfalls
- Rendering untrusted template strings is remote code execution; treat template source as trusted code.
- Disabling autoescape for convenience leaks XSS whenever any field later becomes user-controlled.
- Deep attribute traversal in templates, obj.owner.account.balance, couples markup to model internals.
FAQ
- Why is autoescape so important?
- With autoescape on, Jinja escapes < > & and quotes before values reach HTML, which is the primary defense against template-driven XSS. Turn it off only for genuinely trusted markup, and then sanitize explicitly.
- How do I render templates from user-supplied strings?
- Do not: rendering user-controlled templates is code execution, since templates can call attributes and filters. Render only your own templates and interpolate user data as context values.
- StrictUndefined versus the default?
- The default Undefined renders missing values as empty strings, hiding typos. StrictUndefined raises on missing keys, catching mistakes at the first render instead of shipping silent gaps.
Report a problem with this API docOpens a pre-filled issue on GitHub.