0
# Environment and Templates
1
2
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.
3
4
## Capabilities
5
6
### Environment Configuration
7
8
The Environment class is the central configuration hub for all template operations, managing loaders, filters, tests, globals, and processing options.
9
10
```python { .api }
11
class Environment:
12
def __init__(
13
self,
14
block_start_string='{%',
15
block_end_string='%}',
16
variable_start_string='{{',
17
variable_end_string='}}',
18
comment_start_string='{#',
19
comment_end_string='#}',
20
line_statement_prefix=None,
21
line_comment_prefix=None,
22
trim_blocks=False,
23
lstrip_blocks=False,
24
newline_sequence='\n',
25
keep_trailing_newline=False,
26
extensions=(),
27
optimized=True,
28
undefined=Undefined,
29
finalize=None,
30
autoescape=False,
31
loader=None,
32
cache_size=400,
33
auto_reload=True,
34
bytecode_cache=None,
35
enable_async=False
36
):
37
"""
38
Initialize template environment with configuration options.
39
40
Parameters:
41
block_start_string: Start of block tags (default: '{%')
42
block_end_string: End of block tags (default: '%}')
43
variable_start_string: Start of variable tags (default: '{{')
44
variable_end_string: End of variable tags (default: '}}')
45
comment_start_string: Start of comment tags (default: '{#')
46
comment_end_string: End of comment tags (default: '#}')
47
line_statement_prefix: Prefix for line statements
48
line_comment_prefix: Prefix for line comments
49
trim_blocks: Remove first newline after blocks
50
lstrip_blocks: Strip leading spaces/tabs from line after blocks
51
newline_sequence: Newline sequence ('\n', '\r\n', or '\r')
52
keep_trailing_newline: Preserve trailing newlines
53
extensions: List of extension instances or names
54
optimized: Enable optimizations
55
undefined: Undefined class to use for missing variables
56
finalize: Function to process all template variables
57
autoescape: Enable automatic HTML escaping (bool or callable)
58
loader: Template loader instance
59
cache_size: Template cache size (0 to disable)
60
auto_reload: Auto-reload templates when changed
61
bytecode_cache: Bytecode cache instance
62
enable_async: Enable async template execution
63
"""
64
```
65
66
### Environment Methods
67
68
Environment provides methods for template loading, compilation, and environment management.
69
70
```python { .api }
71
def get_template(self, name, parent=None, globals=None):
72
"""
73
Load a template by name.
74
75
Parameters:
76
name: Template name
77
parent: Parent template name for inheritance context
78
globals: Additional globals for this template
79
80
Returns:
81
Template: Compiled template instance
82
83
Raises:
84
TemplateNotFound: If template doesn't exist
85
"""
86
87
def select_template(self, names, parent=None, globals=None):
88
"""
89
Load first available template from a list of names.
90
91
Parameters:
92
names: List of template names to try
93
parent: Parent template name for inheritance context
94
globals: Additional globals for this template
95
96
Returns:
97
Template: First found compiled template
98
99
Raises:
100
TemplatesNotFound: If no templates exist
101
"""
102
103
def get_or_select_template(self, template_name_or_list, parent=None, globals=None):
104
"""
105
Load single template or first from list.
106
107
Parameters:
108
template_name_or_list: Template name or list of names
109
parent: Parent template name for inheritance context
110
globals: Additional globals for this template
111
112
Returns:
113
Template: Compiled template instance
114
"""
115
116
def from_string(self, source, globals=None, template_class=None):
117
"""
118
Load template from string source.
119
120
Parameters:
121
source: Template source code
122
globals: Additional globals for this template
123
template_class: Custom template class to use
124
125
Returns:
126
Template: Compiled template instance
127
"""
128
129
def compile(self, source, name=None, filename=None, raw=False, defer_init=False):
130
"""
131
Compile template source to Python code.
132
133
Parameters:
134
source: Template source code
135
name: Template name for debugging
136
filename: Template filename for debugging
137
raw: Return raw code without wrapper
138
defer_init: Defer template initialization
139
140
Returns:
141
Template or code: Compiled template or code
142
"""
143
144
def compile_expression(self, source, undefined_to_none=True):
145
"""
146
Compile standalone expression.
147
148
Parameters:
149
source: Expression source code
150
undefined_to_none: Convert undefined to None
151
152
Returns:
153
TemplateExpression: Compiled expression
154
"""
155
156
def compile_templates(self, target, extensions=None, filter_func=None, zip=None, log_function=None, ignore_errors=True, py_compile=False):
157
"""
158
Compile all templates to target directory or zip file.
159
160
Parameters:
161
target: Target directory or zip file path
162
extensions: File extensions to include
163
filter_func: Function to filter template names
164
zip: Create zip file instead of directory
165
log_function: Function for logging compilation progress
166
ignore_errors: Continue on compilation errors
167
py_compile: Compile Python bytecode files
168
"""
169
170
def list_templates(self, extensions=None, filter_func=None):
171
"""
172
List all available templates.
173
174
Parameters:
175
extensions: File extensions to include
176
filter_func: Function to filter template names
177
178
Returns:
179
list: List of template names
180
"""
181
182
def add_extension(self, extension):
183
"""
184
Add extension after environment creation.
185
186
Parameters:
187
extension: Extension instance or name
188
"""
189
190
def extend(self, **attributes):
191
"""
192
Add attributes to environment.
193
194
Parameters:
195
**attributes: Attributes to add to environment
196
"""
197
198
def overlay(self, **options):
199
"""
200
Create overlay environment with modified options.
201
202
Parameters:
203
**options: Options to override
204
205
Returns:
206
Environment: New environment with modified options
207
"""
208
```
209
210
### Template Rendering
211
212
Template objects provide multiple rendering modes for different use cases including synchronous/asynchronous rendering and streaming output.
213
214
```python { .api }
215
class Template:
216
def render(self, *args, **kwargs):
217
"""
218
Render template to string.
219
220
Parameters:
221
*args: Positional context variables
222
**kwargs: Named context variables
223
224
Returns:
225
str: Rendered template output
226
"""
227
228
def render_async(self, *args, **kwargs):
229
"""
230
Async version of render().
231
232
Parameters:
233
*args: Positional context variables
234
**kwargs: Named context variables
235
236
Returns:
237
str: Rendered template output (awaitable)
238
"""
239
240
def stream(self, *args, **kwargs):
241
"""
242
Return TemplateStream for streaming output.
243
244
Parameters:
245
*args: Positional context variables
246
**kwargs: Named context variables
247
248
Returns:
249
TemplateStream: Streaming template output
250
"""
251
252
def generate(self, *args, **kwargs):
253
"""
254
Generate template parts as iterator.
255
256
Parameters:
257
*args: Positional context variables
258
**kwargs: Named context variables
259
260
Returns:
261
Iterator[str]: Template output parts
262
"""
263
264
def generate_async(self, *args, **kwargs):
265
"""
266
Async version of generate().
267
268
Parameters:
269
*args: Positional context variables
270
**kwargs: Named context variables
271
272
Returns:
273
AsyncIterator[str]: Template output parts (awaitable)
274
"""
275
```
276
277
### Context Management
278
279
Template execution contexts manage variable scoping, template globals, and runtime environments.
280
281
```python { .api }
282
def new_context(self, vars=None, shared=False, locals=None):
283
"""
284
Create new template context.
285
286
Parameters:
287
vars: Context variables dictionary
288
shared: Share parent context
289
locals: Local variables dictionary
290
291
Returns:
292
Context: New template context
293
"""
294
295
def make_module(self, vars=None, shared=False, locals=None):
296
"""
297
Create template module for accessing exported variables/macros.
298
299
Parameters:
300
vars: Context variables dictionary
301
shared: Share parent context
302
locals: Local variables dictionary
303
304
Returns:
305
TemplateModule: Template module instance
306
"""
307
308
def make_module_async(self, vars=None, shared=False, locals=None):
309
"""
310
Async version of make_module().
311
312
Parameters:
313
vars: Context variables dictionary
314
shared: Share parent context
315
locals: Local variables dictionary
316
317
Returns:
318
TemplateModule: Template module instance (awaitable)
319
"""
320
```
321
322
### Parsing and Processing
323
324
Low-level template parsing and preprocessing functionality for advanced use cases and extension development.
325
326
```python { .api }
327
def parse(self, source, name=None, filename=None):
328
"""
329
Parse template source to AST.
330
331
Parameters:
332
source: Template source code
333
name: Template name for debugging
334
filename: Template filename for debugging
335
336
Returns:
337
AST: Template abstract syntax tree
338
"""
339
340
def lex(self, source, name=None, filename=None):
341
"""
342
Tokenize template source.
343
344
Parameters:
345
source: Template source code
346
name: Template name for debugging
347
filename: Template filename for debugging
348
349
Returns:
350
Iterator: Token stream
351
"""
352
353
def preprocess(self, source, name=None, filename=None):
354
"""
355
Preprocess template source with extensions.
356
357
Parameters:
358
source: Template source code
359
name: Template name for debugging
360
filename: Template filename for debugging
361
362
Returns:
363
str: Preprocessed template source
364
"""
365
```
366
367
### Filter and Test Execution
368
369
Direct access to template filters and tests for programmatic use outside of template rendering.
370
371
```python { .api }
372
def call_filter(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None):
373
"""
374
Invoke template filter.
375
376
Parameters:
377
name: Filter name
378
value: Value to filter
379
args: Filter arguments
380
kwargs: Filter keyword arguments
381
context: Template context
382
eval_ctx: Evaluation context
383
384
Returns:
385
Any: Filtered value
386
"""
387
388
def call_test(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None):
389
"""
390
Invoke template test.
391
392
Parameters:
393
name: Test name
394
value: Value to test
395
args: Test arguments
396
kwargs: Test keyword arguments
397
context: Template context
398
eval_ctx: Evaluation context
399
400
Returns:
401
bool: Test result
402
"""
403
```
404
405
### Utility Functions
406
407
Essential utility functions for template development, custom filters/tests, and environment management.
408
409
```python { .api }
410
def pass_context(f):
411
"""
412
Decorator to pass the current template Context as the first argument
413
to the decorated function when called while rendering a template.
414
415
Can be used on functions, filters, and tests.
416
417
Parameters:
418
f: Function to decorate
419
420
Returns:
421
Decorated function that receives Context as first argument
422
"""
423
424
def pass_eval_context(f):
425
"""
426
Decorator to pass the current EvaluationContext as the first argument
427
to the decorated function when called while rendering a template.
428
429
Use when only the evaluation context is needed, not the full Context.
430
431
Parameters:
432
f: Function to decorate
433
434
Returns:
435
Decorated function that receives EvaluationContext as first argument
436
"""
437
438
def pass_environment(f):
439
"""
440
Decorator to pass the current Environment as the first argument
441
to the decorated function when called while rendering a template.
442
443
Use when only the environment is needed, not the full Context.
444
445
Parameters:
446
f: Function to decorate
447
448
Returns:
449
Decorated function that receives Environment as first argument
450
"""
451
452
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False):
453
"""
454
Utility function for configuring autoescape behavior based on template names.
455
456
Parameters:
457
enabled_extensions: File extensions where autoescape is enabled
458
disabled_extensions: File extensions where autoescape is disabled
459
default_for_string: Default autoescape for string templates
460
default: Default autoescape when extension doesn't match
461
462
Returns:
463
Callable that determines autoescape setting for templates
464
"""
465
466
def clear_caches():
467
"""
468
Clear all internal template caches.
469
470
This includes the global template cache and any other internal caches
471
that Jinja2 uses for optimization.
472
"""
473
474
def is_undefined(obj):
475
"""
476
Check if an object is an undefined object.
477
478
Parameters:
479
obj: Object to test
480
481
Returns:
482
bool: True if object is an Undefined instance
483
"""
484
```
485
486
## Types
487
488
```python { .api }
489
class TemplateStream:
490
"""
491
Streaming template output that can be iterated or written to file-like objects.
492
493
Methods:
494
dump(fp): Write stream to file-like object
495
disable_buffering(): Disable output buffering
496
enable_buffering(size=5): Enable output buffering
497
"""
498
499
class TemplateModule:
500
"""
501
Template module providing access to exported variables and macros.
502
503
Attributes contain all variables and macros exported by the template.
504
"""
505
506
class TemplateExpression:
507
"""
508
Compiled standalone expression that can be evaluated with context.
509
510
Methods:
511
__call__(**context): Evaluate expression with context variables
512
"""
513
```