Typing Stubs for Jinja2

2.11.9 · active · verified Thu Apr 09

types-jinja2 is a PEP 561 type stub package that provides type annotations for the Jinja2 templating engine. It enables static type-checking tools like mypy, PyCharm, and pytype to analyze code that uses Jinja2 for improved code quality and early error detection. This package is part of the `python/typeshed` monorepo and is automatically released multiple times a day when updates are needed.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic Jinja2 usage. When `types-jinja2` is installed, a type checker like mypy will use these stubs to analyze the Jinja2 code, ensuring type correctness for `Environment`, `Template`, and their methods.

from jinja2 import Environment, FileSystemLoader
import os

# Create a dummy template file for the example
with open('hello.html', 'w') as f:
    f.write('Hello, {{ name }}! Today is {{ date }}.')

# Set up the Jinja2 environment
# In a real application, ensure `template_dir` points to your templates directory
template_dir = os.path.dirname(os.path.abspath(__file__))
env = Environment(loader=FileSystemLoader(template_dir))

# Load and render a template
template = env.get_template('hello.html')
output = template.render(name='World', date='2026-04-09')
print(output)

# Example with missing variable (mypy would flag this if types-jinja2 is active)
# try:
#     template.render(name='Jinja') # 'date' is missing, mypy would warn
# except Exception as e:
#     print(f"Rendering with missing data (expected by mypy): {e}")

# Clean up the dummy file
os.remove('hello.html')

view raw JSON →