Jinja2

3.1.6 · active · verified Sat Mar 28

Jinja2 is a fast, expressive, extensible templating engine for Python. Special placeholders in templates allow writing code similar to Python syntax, which is then rendered against passed data to produce a final document. It supports template inheritance, macros, autoescaping, sandboxed execution, async rendering, and i18n via Babel. Current stable version is 3.1.6 (a security patch release); the 3.1.x branch receives active bugfix and security updates with no fixed cadence.

Warnings

Install

Imports

Quickstart

Basic Environment setup and template rendering, demonstrating safe autoescape configuration for HTML and plain-text contexts.

from jinja2 import Environment, FileSystemLoader, select_autoescape

# Always set autoescape explicitly; default is False which is a security risk for HTML output
env = Environment(
    loader=FileSystemLoader("."),
    autoescape=select_autoescape(["html", "htm", "xml"]),
)

# Render from a string (autoescape=False for non-HTML plain text)
text_env = Environment()
template = text_env.from_string("Hello, {{ name }}! You have {{ count }} message(s).")
result = template.render(name="World", count=3)
print(result)
# -> Hello, World! You have 3 message(s).

# Render an HTML template string safely
html_env = Environment(autoescape=True)
html_tmpl = html_env.from_string("<p>Hello, {{ name }}!</p>")
print(html_tmpl.render(name="<script>alert(1)</script>"))
# -> <p>Hello, &lt;script&gt;alert(1)&lt;/script&gt;!</p>

view raw JSON →