A very fast and expressive template engine for Python applications
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
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.
The Environment class is the central configuration hub for all template operations, managing loaders, filters, tests, globals, and processing options.
class Environment:
def __init__(
self,
block_start_string='{%',
block_end_string='%}',
variable_start_string='{{',
variable_end_string='}}',
comment_start_string='{#',
comment_end_string='#}',
line_statement_prefix=None,
line_comment_prefix=None,
trim_blocks=False,
lstrip_blocks=False,
newline_sequence='\n',
keep_trailing_newline=False,
extensions=(),
optimized=True,
undefined=Undefined,
finalize=None,
autoescape=False,
loader=None,
cache_size=400,
auto_reload=True,
bytecode_cache=None,
enable_async=False
):
"""
Initialize template environment with configuration options.
Parameters:
block_start_string: Start of block tags (default: '{%')
block_end_string: End of block tags (default: '%}')
variable_start_string: Start of variable tags (default: '{{')
variable_end_string: End of variable tags (default: '}}')
comment_start_string: Start of comment tags (default: '{#')
comment_end_string: End of comment tags (default: '#}')
line_statement_prefix: Prefix for line statements
line_comment_prefix: Prefix for line comments
trim_blocks: Remove first newline after blocks
lstrip_blocks: Strip leading spaces/tabs from line after blocks
newline_sequence: Newline sequence ('\n', '\r\n', or '\r')
keep_trailing_newline: Preserve trailing newlines
extensions: List of extension instances or names
optimized: Enable optimizations
undefined: Undefined class to use for missing variables
finalize: Function to process all template variables
autoescape: Enable automatic HTML escaping (bool or callable)
loader: Template loader instance
cache_size: Template cache size (0 to disable)
auto_reload: Auto-reload templates when changed
bytecode_cache: Bytecode cache instance
enable_async: Enable async template execution
"""Environment provides methods for template loading, compilation, and environment management.
def get_template(self, name, parent=None, globals=None):
"""
Load a template by name.
Parameters:
name: Template name
parent: Parent template name for inheritance context
globals: Additional globals for this template
Returns:
Template: Compiled template instance
Raises:
TemplateNotFound: If template doesn't exist
"""
def select_template(self, names, parent=None, globals=None):
"""
Load first available template from a list of names.
Parameters:
names: List of template names to try
parent: Parent template name for inheritance context
globals: Additional globals for this template
Returns:
Template: First found compiled template
Raises:
TemplatesNotFound: If no templates exist
"""
def get_or_select_template(self, template_name_or_list, parent=None, globals=None):
"""
Load single template or first from list.
Parameters:
template_name_or_list: Template name or list of names
parent: Parent template name for inheritance context
globals: Additional globals for this template
Returns:
Template: Compiled template instance
"""
def from_string(self, source, globals=None, template_class=None):
"""
Load template from string source.
Parameters:
source: Template source code
globals: Additional globals for this template
template_class: Custom template class to use
Returns:
Template: Compiled template instance
"""
def compile(self, source, name=None, filename=None, raw=False, defer_init=False):
"""
Compile template source to Python code.
Parameters:
source: Template source code
name: Template name for debugging
filename: Template filename for debugging
raw: Return raw code without wrapper
defer_init: Defer template initialization
Returns:
Template or code: Compiled template or code
"""
def compile_expression(self, source, undefined_to_none=True):
"""
Compile standalone expression.
Parameters:
source: Expression source code
undefined_to_none: Convert undefined to None
Returns:
TemplateExpression: Compiled expression
"""
def compile_templates(self, target, extensions=None, filter_func=None, zip=None, log_function=None, ignore_errors=True, py_compile=False):
"""
Compile all templates to target directory or zip file.
Parameters:
target: Target directory or zip file path
extensions: File extensions to include
filter_func: Function to filter template names
zip: Create zip file instead of directory
log_function: Function for logging compilation progress
ignore_errors: Continue on compilation errors
py_compile: Compile Python bytecode files
"""
def list_templates(self, extensions=None, filter_func=None):
"""
List all available templates.
Parameters:
extensions: File extensions to include
filter_func: Function to filter template names
Returns:
list: List of template names
"""
def add_extension(self, extension):
"""
Add extension after environment creation.
Parameters:
extension: Extension instance or name
"""
def extend(self, **attributes):
"""
Add attributes to environment.
Parameters:
**attributes: Attributes to add to environment
"""
def overlay(self, **options):
"""
Create overlay environment with modified options.
Parameters:
**options: Options to override
Returns:
Environment: New environment with modified options
"""Template objects provide multiple rendering modes for different use cases including synchronous/asynchronous rendering and streaming output.
class Template:
def render(self, *args, **kwargs):
"""
Render template to string.
Parameters:
*args: Positional context variables
**kwargs: Named context variables
Returns:
str: Rendered template output
"""
def render_async(self, *args, **kwargs):
"""
Async version of render().
Parameters:
*args: Positional context variables
**kwargs: Named context variables
Returns:
str: Rendered template output (awaitable)
"""
def stream(self, *args, **kwargs):
"""
Return TemplateStream for streaming output.
Parameters:
*args: Positional context variables
**kwargs: Named context variables
Returns:
TemplateStream: Streaming template output
"""
def generate(self, *args, **kwargs):
"""
Generate template parts as iterator.
Parameters:
*args: Positional context variables
**kwargs: Named context variables
Returns:
Iterator[str]: Template output parts
"""
def generate_async(self, *args, **kwargs):
"""
Async version of generate().
Parameters:
*args: Positional context variables
**kwargs: Named context variables
Returns:
AsyncIterator[str]: Template output parts (awaitable)
"""Template execution contexts manage variable scoping, template globals, and runtime environments.
def new_context(self, vars=None, shared=False, locals=None):
"""
Create new template context.
Parameters:
vars: Context variables dictionary
shared: Share parent context
locals: Local variables dictionary
Returns:
Context: New template context
"""
def make_module(self, vars=None, shared=False, locals=None):
"""
Create template module for accessing exported variables/macros.
Parameters:
vars: Context variables dictionary
shared: Share parent context
locals: Local variables dictionary
Returns:
TemplateModule: Template module instance
"""
def make_module_async(self, vars=None, shared=False, locals=None):
"""
Async version of make_module().
Parameters:
vars: Context variables dictionary
shared: Share parent context
locals: Local variables dictionary
Returns:
TemplateModule: Template module instance (awaitable)
"""Low-level template parsing and preprocessing functionality for advanced use cases and extension development.
def parse(self, source, name=None, filename=None):
"""
Parse template source to AST.
Parameters:
source: Template source code
name: Template name for debugging
filename: Template filename for debugging
Returns:
AST: Template abstract syntax tree
"""
def lex(self, source, name=None, filename=None):
"""
Tokenize template source.
Parameters:
source: Template source code
name: Template name for debugging
filename: Template filename for debugging
Returns:
Iterator: Token stream
"""
def preprocess(self, source, name=None, filename=None):
"""
Preprocess template source with extensions.
Parameters:
source: Template source code
name: Template name for debugging
filename: Template filename for debugging
Returns:
str: Preprocessed template source
"""Direct access to template filters and tests for programmatic use outside of template rendering.
def call_filter(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None):
"""
Invoke template filter.
Parameters:
name: Filter name
value: Value to filter
args: Filter arguments
kwargs: Filter keyword arguments
context: Template context
eval_ctx: Evaluation context
Returns:
Any: Filtered value
"""
def call_test(self, name, value, args=None, kwargs=None, context=None, eval_ctx=None):
"""
Invoke template test.
Parameters:
name: Test name
value: Value to test
args: Test arguments
kwargs: Test keyword arguments
context: Template context
eval_ctx: Evaluation context
Returns:
bool: Test result
"""Essential utility functions for template development, custom filters/tests, and environment management.
def pass_context(f):
"""
Decorator to pass the current template Context as the first argument
to the decorated function when called while rendering a template.
Can be used on functions, filters, and tests.
Parameters:
f: Function to decorate
Returns:
Decorated function that receives Context as first argument
"""
def pass_eval_context(f):
"""
Decorator to pass the current EvaluationContext as the first argument
to the decorated function when called while rendering a template.
Use when only the evaluation context is needed, not the full Context.
Parameters:
f: Function to decorate
Returns:
Decorated function that receives EvaluationContext as first argument
"""
def pass_environment(f):
"""
Decorator to pass the current Environment as the first argument
to the decorated function when called while rendering a template.
Use when only the environment is needed, not the full Context.
Parameters:
f: Function to decorate
Returns:
Decorated function that receives Environment as first argument
"""
def select_autoescape(enabled_extensions=('html', 'htm', 'xml'), disabled_extensions=(), default_for_string=True, default=False):
"""
Utility function for configuring autoescape behavior based on template names.
Parameters:
enabled_extensions: File extensions where autoescape is enabled
disabled_extensions: File extensions where autoescape is disabled
default_for_string: Default autoescape for string templates
default: Default autoescape when extension doesn't match
Returns:
Callable that determines autoescape setting for templates
"""
def clear_caches():
"""
Clear all internal template caches.
This includes the global template cache and any other internal caches
that Jinja2 uses for optimization.
"""
def is_undefined(obj):
"""
Check if an object is an undefined object.
Parameters:
obj: Object to test
Returns:
bool: True if object is an Undefined instance
"""class TemplateStream:
"""
Streaming template output that can be iterated or written to file-like objects.
Methods:
dump(fp): Write stream to file-like object
disable_buffering(): Disable output buffering
enable_buffering(size=5): Enable output buffering
"""
class TemplateModule:
"""
Template module providing access to exported variables and macros.
Attributes contain all variables and macros exported by the template.
"""
class TemplateExpression:
"""
Compiled standalone expression that can be evaluated with context.
Methods:
__call__(**context): Evaluate expression with context variables
"""