A very fast and expressive template engine for Python applications
npx @tessl/cli install tessl/pypi-jinja2@3.1.00
# Jinja2
1
2
A comprehensive Python template engine that provides fast, expressive, and extensible templating capabilities for web applications and other software projects. Jinja2 features template inheritance, macro systems, HTML autoescaping for XSS prevention, sandboxed environments for safe template execution, AsyncIO support, internationalization with Babel, just-in-time compilation with caching, precise error reporting, and extensible filters and functions.
3
4
## Package Information
5
6
- **Package Name**: Jinja2
7
- **Language**: Python
8
- **Installation**: `pip install Jinja2`
9
10
## Core Imports
11
12
```python
13
import jinja2
14
```
15
16
Common patterns for working with templates:
17
18
```python
19
from jinja2 import Environment, FileSystemLoader, Template
20
```
21
22
Import specific components:
23
24
```python
25
from jinja2 import (
26
Environment, Template, FileSystemLoader, DictLoader,
27
TemplateNotFound, TemplateSyntaxError, select_autoescape
28
)
29
```
30
31
Import native types for native Python value rendering:
32
33
```python
34
from jinja2.nativetypes import NativeEnvironment, NativeTemplate
35
```
36
37
Import meta analysis functions for template introspection:
38
39
```python
40
from jinja2 import meta
41
```
42
43
Enable async template support by setting `enable_async=True` in Environment:
44
45
```python
46
from jinja2 import Environment
47
env = Environment(enable_async=True)
48
```
49
50
## Basic Usage
51
52
```python
53
from jinja2 import Environment, FileSystemLoader, Template
54
55
# Method 1: Create template from string
56
template = Template('Hello {{ name }}!')
57
result = template.render(name='World')
58
print(result) # Output: Hello World!
59
60
# Method 2: Load from filesystem
61
env = Environment(loader=FileSystemLoader('templates'))
62
template = env.get_template('hello.html')
63
result = template.render(name='World', items=['apple', 'banana'])
64
65
# Method 3: Create environment with options
66
env = Environment(
67
loader=FileSystemLoader('templates'),
68
autoescape=select_autoescape(['html', 'xml']),
69
trim_blocks=True,
70
lstrip_blocks=True
71
)
72
template = env.get_template('page.html')
73
result = template.render(title='My Page', content='Hello World')
74
75
# Method 4: Async template rendering
76
import asyncio
77
78
async def render_async_template():
79
env = Environment(
80
loader=FileSystemLoader('templates'),
81
enable_async=True
82
)
83
template = env.get_template('async_page.html')
84
result = await template.render_async(title='Async Page', data='Hello Async World')
85
return result
86
87
# Run async template
88
result = asyncio.run(render_async_template())
89
```
90
91
## Architecture
92
93
Jinja2's architecture is built around several key components that work together to provide flexible and secure template processing:
94
95
- **Environment**: Central configuration hub that manages loaders, filters, tests, globals, and processing options
96
- **Template**: Compiled template objects that can be rendered with context data multiple times efficiently
97
- **Loaders**: Pluggable template loading system supporting filesystem, package, dictionary, and custom sources
98
- **Context**: Runtime execution environment that manages variable scoping and template globals
99
- **Filters and Tests**: Extensible processing functions for data transformation and conditional logic
100
- **Extensions**: Plugin system for adding custom template syntax and functionality
101
- **Bytecode Cache**: Optional performance optimization that caches compiled templates
102
- **Sandbox**: Security layer that restricts template access to unsafe Python operations
103
104
This modular design enables Jinja2 to serve as the template engine for major web frameworks (Flask, Django), content management systems, configuration generation tools, and any application requiring dynamic text generation with a secure, Python-like syntax.
105
106
## Capabilities
107
108
### Environment and Template Management
109
110
Core functionality for creating template environments, loading and compiling templates, and managing template execution contexts. The Environment class serves as the central configuration point for all template operations.
111
112
```python { .api }
113
class Environment:
114
def __init__(self, **options): ...
115
def get_template(self, name, parent=None, globals=None): ...
116
def from_string(self, source, globals=None, template_class=None): ...
117
def compile(self, source, name=None, filename=None, raw=False, defer_init=False): ...
118
119
class Template:
120
def render(*args, **kwargs): ...
121
def render_async(*args, **kwargs): ...
122
def stream(*args, **kwargs): ...
123
```
124
125
[Environment and Templates](./environment-templates.md)
126
127
### Template Loaders
128
129
Flexible template loading system supporting multiple sources including filesystem directories, Python packages, dictionaries, and custom loading functions. Loaders can be combined and configured for complex template discovery patterns.
130
131
```python { .api }
132
class FileSystemLoader:
133
def __init__(self, searchpath, encoding='utf-8', followlinks=False): ...
134
135
class PackageLoader:
136
def __init__(self, package_name, package_path='templates', encoding='utf-8'): ...
137
138
class DictLoader:
139
def __init__(self, mapping): ...
140
141
class ChoiceLoader:
142
def __init__(self, loaders): ...
143
```
144
145
[Template Loaders](./template-loaders.md)
146
147
### Filters and Data Processing
148
149
Comprehensive collection of 54 built-in filters for data transformation including string processing, sequence manipulation, numeric operations, and object formatting. Filters can be chained and custom filters can be added to environments.
150
151
```python { .api }
152
# String filters
153
def escape(s): ... # HTML escape
154
def upper(s): ... # Convert to uppercase
155
def lower(s): ... # Convert to lowercase
156
def title(s): ... # Title case
157
158
# Sequence filters
159
def join(seq, separator=''): ... # Join sequence
160
def sort(seq, case_sensitive=True, attribute=None): ... # Sort sequence
161
def unique(seq, case_sensitive=True, attribute=None): ... # Get unique items
162
163
# Numeric filters
164
def round(number, precision=0, method='common'): ... # Round number
165
def sum(seq, attribute=None, start=0): ... # Sum sequence
166
```
167
168
[Filters and Data Processing](./filters-data-processing.md)
169
170
### Tests and Conditionals
171
172
39 built-in tests for template conditional logic including type checking, value comparison, and meta-testing. Tests are used in {% if %} statements and can be combined with logical operators.
173
174
```python { .api }
175
# Type tests
176
def defined(obj): ... # Check if defined
177
def undefined(obj): ... # Check if undefined
178
def string(obj): ... # Check if string
179
def number(obj): ... # Check if number
180
181
# Value tests
182
def even(value): ... # Check if even
183
def odd(value): ... # Check if odd
184
def divisibleby(value, num): ... # Check divisibility
185
186
# Comparison tests
187
def equalto(value, other): ... # Equality test
188
def greaterthan(value, other): ... # Greater than test
189
```
190
191
[Tests and Conditionals](./tests-conditionals.md)
192
193
### Extensions and Custom Syntax
194
195
Extensible plugin system for adding custom template syntax, processing logic, and integration with external tools. Includes built-in extensions for internationalization, loop controls, expression statements, and debugging.
196
197
```python { .api }
198
class Extension:
199
def __init__(self, environment): ...
200
def preprocess(self, source, name, filename=None): ...
201
def parse(self, parser): ...
202
203
class InternationalizationExtension(Extension): ... # i18n support
204
class LoopControlsExtension(Extension): ... # break/continue
205
class ExprStmtExtension(Extension): ... # {% do %} tag
206
class DebugExtension(Extension): ... # {% debug %} tag
207
```
208
209
[Extensions and Custom Syntax](./extensions-custom-syntax.md)
210
211
### Bytecode Caching
212
213
Performance optimization system that caches compiled template bytecode to filesystem or external storage systems like Memcached. Significantly improves template loading performance in production environments.
214
215
```python { .api }
216
class BytecodeCache:
217
def load_bytecode(self, bucket): ...
218
def dump_bytecode(self, bucket): ...
219
def clear(): ...
220
221
class FileSystemBytecodeCache(BytecodeCache):
222
def __init__(self, directory=None, pattern='__jinja2_%s.cache'): ...
223
224
class MemcachedBytecodeCache(BytecodeCache):
225
def __init__(self, client, prefix='jinja2/bytecode/', timeout=None): ...
226
```
227
228
[Bytecode Caching](./bytecode-caching.md)
229
230
### Security and Sandboxing
231
232
Security framework for safely executing untrusted templates by restricting access to dangerous Python operations and attributes. Includes configurable policies and safe alternatives for common operations.
233
234
```python { .api }
235
class SandboxedEnvironment(Environment):
236
def __init__(self, **options): ...
237
238
def safe_range(*args): ... # Safe range function with limits
239
def is_internal_attribute(obj, attr): ... # Check if attribute is internal
240
def modifies_known_mutable(obj, attr): ... # Check if method modifies objects
241
```
242
243
[Security and Sandboxing](./security-sandboxing.md)
244
245
### Error Handling and Debugging
246
247
Comprehensive exception hierarchy and debugging tools for template development including detailed error messages, source location tracking, and runtime debugging capabilities.
248
249
```python { .api }
250
class TemplateError(Exception): ...
251
class TemplateNotFound(TemplateError): ...
252
class TemplateSyntaxError(TemplateError): ...
253
class TemplateRuntimeError(TemplateError): ...
254
class UndefinedError(TemplateRuntimeError): ...
255
256
class DebugUndefined(Undefined): ... # Debug undefined values
257
def make_logging_undefined(logger=None, base=None): ... # Logging undefined
258
```
259
260
[Error Handling and Debugging](./error-handling-debugging.md)
261
262
### Native Types
263
264
Specialized template environments that render templates to native Python types instead of strings. Returns actual Python objects (integers, lists, dictionaries, etc.) when possible, with string fallback for complex expressions.
265
266
```python { .api }
267
class NativeEnvironment(Environment):
268
def __init__(self, **options): ...
269
270
class NativeTemplate(Template):
271
def render(self, *args, **kwargs): ...
272
def render_async(self, *args, **kwargs): ...
273
```
274
275
[Native Types](./native-types.md)
276
277
### Meta Analysis
278
279
Template introspection functions for analyzing template dependencies and variable usage. Useful for dependency tracking, caching systems, and development tools.
280
281
```python { .api }
282
def find_undeclared_variables(ast): ... # Find template variables
283
def find_referenced_templates(ast): ... # Find template dependencies
284
```
285
286
[Meta Analysis](./meta-analysis.md)
287
288
## Types
289
290
```python { .api }
291
class Environment:
292
"""
293
Core template environment for configuration and template loading.
294
295
Attributes:
296
block_start_string: Block start delimiter (default: '{%')
297
block_end_string: Block end delimiter (default: '%}')
298
variable_start_string: Variable start delimiter (default: '{{')
299
variable_end_string: Variable end delimiter (default: '}}')
300
comment_start_string: Comment start delimiter (default: '{#')
301
comment_end_string: Comment end delimiter (default: '#}')
302
trim_blocks: Remove first newline after blocks
303
lstrip_blocks: Strip leading spaces/tabs from line after blocks
304
autoescape: Enable automatic HTML escaping
305
loader: Template loader instance
306
undefined: Undefined class to use
307
finalize: Final value processing function
308
filters: Dictionary of available filters
309
tests: Dictionary of available tests
310
globals: Dictionary of global variables
311
"""
312
313
class Template:
314
"""
315
Compiled template that can be rendered with context data.
316
317
Attributes:
318
environment: Associated Environment instance
319
name: Template name
320
filename: Template filename
321
globals: Template globals
322
module: Template as module (for accessing exported variables/macros)
323
"""
324
325
class TemplateError(Exception):
326
"""Base class for all template-related errors."""
327
328
class TemplateNotFound(TemplateError):
329
"""Template could not be found."""
330
331
class TemplateSyntaxError(TemplateError):
332
"""Template syntax is malformed."""
333
334
class TemplateRuntimeError(TemplateError):
335
"""Generic runtime error during template execution."""
336
337
class UndefinedError(TemplateRuntimeError):
338
"""Undefined variable accessed inappropriately."""
339
340
class SecurityError(TemplateRuntimeError):
341
"""Template tried to perform insecure operations in sandbox mode."""
342
343
class FilterArgumentError(TemplateRuntimeError):
344
"""Filter called with inappropriate arguments."""
345
346
class Undefined:
347
"""Default undefined type that raises errors on most operations."""
348
349
class StrictUndefined(Undefined):
350
"""Undefined that raises errors on any operation."""
351
352
class DebugUndefined(Undefined):
353
"""Undefined that shows debug info when printed."""
354
355
class ChainableUndefined(Undefined):
356
"""Undefined that doesn't raise on getattr/getitem operations."""
357
```