# Jinja2

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.

## Package Information

- **Package Name**: Jinja2
- **Language**: Python
- **Installation**: `pip install Jinja2`

## Core Imports

```python
import jinja2
```

Common patterns for working with templates:

```python
from jinja2 import Environment, FileSystemLoader, Template
```

Import specific components:

```python
from jinja2 import (
    Environment, Template, FileSystemLoader, DictLoader,
    TemplateNotFound, TemplateSyntaxError, select_autoescape
)
```

Import native types for native Python value rendering:

```python
from jinja2.nativetypes import NativeEnvironment, NativeTemplate
```

Import meta analysis functions for template introspection:

```python
from jinja2 import meta
```

Enable async template support by setting `enable_async=True` in Environment:

```python
from jinja2 import Environment
env = Environment(enable_async=True)
```

## Basic Usage

```python
from jinja2 import Environment, FileSystemLoader, Template

# Method 1: Create template from string
template = Template('Hello {{ name }}!')
result = template.render(name='World')
print(result)  # Output: Hello World!

# Method 2: Load from filesystem
env = Environment(loader=FileSystemLoader('templates'))
template = env.get_template('hello.html')
result = template.render(name='World', items=['apple', 'banana'])

# Method 3: Create environment with options
env = Environment(
    loader=FileSystemLoader('templates'),
    autoescape=select_autoescape(['html', 'xml']),
    trim_blocks=True,
    lstrip_blocks=True
)
template = env.get_template('page.html')
result = template.render(title='My Page', content='Hello World')

# Method 4: Async template rendering
import asyncio

async def render_async_template():
    env = Environment(
        loader=FileSystemLoader('templates'),
        enable_async=True
    )
    template = env.get_template('async_page.html')
    result = await template.render_async(title='Async Page', data='Hello Async World')
    return result

# Run async template
result = asyncio.run(render_async_template())
```

## Architecture

Jinja2's architecture is built around several key components that work together to provide flexible and secure template processing:

- **Environment**: Central configuration hub that manages loaders, filters, tests, globals, and processing options
- **Template**: Compiled template objects that can be rendered with context data multiple times efficiently
- **Loaders**: Pluggable template loading system supporting filesystem, package, dictionary, and custom sources
- **Context**: Runtime execution environment that manages variable scoping and template globals
- **Filters and Tests**: Extensible processing functions for data transformation and conditional logic
- **Extensions**: Plugin system for adding custom template syntax and functionality
- **Bytecode Cache**: Optional performance optimization that caches compiled templates
- **Sandbox**: Security layer that restricts template access to unsafe Python operations

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.

## Capabilities

### Environment and Template Management

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.

```python { .api }
class Environment:
    def __init__(self, **options): ...
    def get_template(self, name, parent=None, globals=None): ...
    def from_string(self, source, globals=None, template_class=None): ...
    def compile(self, source, name=None, filename=None, raw=False, defer_init=False): ...

class Template:
    def render(*args, **kwargs): ...
    def render_async(*args, **kwargs): ...
    def stream(*args, **kwargs): ...
```

[Environment and Templates](./environment-templates.md)

### Template Loaders

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.

```python { .api }
class FileSystemLoader:
    def __init__(self, searchpath, encoding='utf-8', followlinks=False): ...

class PackageLoader:
    def __init__(self, package_name, package_path='templates', encoding='utf-8'): ...

class DictLoader:
    def __init__(self, mapping): ...

class ChoiceLoader:
    def __init__(self, loaders): ...
```

[Template Loaders](./template-loaders.md)

### Filters and Data Processing

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.

```python { .api }
# String filters
def escape(s): ...  # HTML escape
def upper(s): ...   # Convert to uppercase
def lower(s): ...   # Convert to lowercase
def title(s): ...   # Title case

# Sequence filters  
def join(seq, separator=''): ...  # Join sequence
def sort(seq, case_sensitive=True, attribute=None): ...  # Sort sequence
def unique(seq, case_sensitive=True, attribute=None): ...  # Get unique items

# Numeric filters
def round(number, precision=0, method='common'): ...  # Round number
def sum(seq, attribute=None, start=0): ...  # Sum sequence
```

[Filters and Data Processing](./filters-data-processing.md)

### Tests and Conditionals

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.

```python { .api }
# Type tests
def defined(obj): ...    # Check if defined
def undefined(obj): ...  # Check if undefined
def string(obj): ...     # Check if string
def number(obj): ...     # Check if number

# Value tests
def even(value): ...     # Check if even
def odd(value): ...      # Check if odd
def divisibleby(value, num): ...  # Check divisibility

# Comparison tests
def equalto(value, other): ...     # Equality test
def greaterthan(value, other): ... # Greater than test
```

[Tests and Conditionals](./tests-conditionals.md)

### Extensions and Custom Syntax

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.

```python { .api }
class Extension:
    def __init__(self, environment): ...
    def preprocess(self, source, name, filename=None): ...
    def parse(self, parser): ...

class InternationalizationExtension(Extension): ...  # i18n support
class LoopControlsExtension(Extension): ...          # break/continue  
class ExprStmtExtension(Extension): ...              # {% do %} tag
class DebugExtension(Extension): ...                 # {% debug %} tag
```

[Extensions and Custom Syntax](./extensions-custom-syntax.md)

### Bytecode Caching

Performance optimization system that caches compiled template bytecode to filesystem or external storage systems like Memcached. Significantly improves template loading performance in production environments.

```python { .api }
class BytecodeCache:
    def load_bytecode(self, bucket): ...
    def dump_bytecode(self, bucket): ...
    def clear(): ...

class FileSystemBytecodeCache(BytecodeCache):
    def __init__(self, directory=None, pattern='__jinja2_%s.cache'): ...

class MemcachedBytecodeCache(BytecodeCache):
    def __init__(self, client, prefix='jinja2/bytecode/', timeout=None): ...
```

[Bytecode Caching](./bytecode-caching.md)

### Security and Sandboxing

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.

```python { .api }
class SandboxedEnvironment(Environment):
    def __init__(self, **options): ...

def safe_range(*args): ...  # Safe range function with limits
def is_internal_attribute(obj, attr): ...  # Check if attribute is internal
def modifies_known_mutable(obj, attr): ...  # Check if method modifies objects
```

[Security and Sandboxing](./security-sandboxing.md)

### Error Handling and Debugging

Comprehensive exception hierarchy and debugging tools for template development including detailed error messages, source location tracking, and runtime debugging capabilities.

```python { .api }
class TemplateError(Exception): ...
class TemplateNotFound(TemplateError): ...
class TemplateSyntaxError(TemplateError): ...
class TemplateRuntimeError(TemplateError): ...
class UndefinedError(TemplateRuntimeError): ...

class DebugUndefined(Undefined): ...  # Debug undefined values
def make_logging_undefined(logger=None, base=None): ...  # Logging undefined
```

[Error Handling and Debugging](./error-handling-debugging.md)

### Native Types

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.

```python { .api }
class NativeEnvironment(Environment):
    def __init__(self, **options): ...

class NativeTemplate(Template):
    def render(self, *args, **kwargs): ...
    def render_async(self, *args, **kwargs): ...
```

[Native Types](./native-types.md)

### Meta Analysis

Template introspection functions for analyzing template dependencies and variable usage. Useful for dependency tracking, caching systems, and development tools.

```python { .api }
def find_undeclared_variables(ast): ...  # Find template variables
def find_referenced_templates(ast): ...  # Find template dependencies
```

[Meta Analysis](./meta-analysis.md)

## Types

```python { .api }
class Environment:
    """
    Core template environment for configuration and template loading.
    
    Attributes:
        block_start_string: Block start delimiter (default: '{%')
        block_end_string: Block end delimiter (default: '%}')
        variable_start_string: Variable start delimiter (default: '{{')
        variable_end_string: Variable end delimiter (default: '}}')
        comment_start_string: Comment start delimiter (default: '{#')
        comment_end_string: Comment end delimiter (default: '#}')
        trim_blocks: Remove first newline after blocks
        lstrip_blocks: Strip leading spaces/tabs from line after blocks
        autoescape: Enable automatic HTML escaping
        loader: Template loader instance
        undefined: Undefined class to use
        finalize: Final value processing function
        filters: Dictionary of available filters
        tests: Dictionary of available tests
        globals: Dictionary of global variables
    """

class Template:
    """
    Compiled template that can be rendered with context data.
    
    Attributes:
        environment: Associated Environment instance
        name: Template name
        filename: Template filename
        globals: Template globals
        module: Template as module (for accessing exported variables/macros)
    """

class TemplateError(Exception):
    """Base class for all template-related errors."""

class TemplateNotFound(TemplateError):
    """Template could not be found."""
    
class TemplateSyntaxError(TemplateError):
    """Template syntax is malformed."""

class TemplateRuntimeError(TemplateError):
    """Generic runtime error during template execution."""

class UndefinedError(TemplateRuntimeError):
    """Undefined variable accessed inappropriately."""

class SecurityError(TemplateRuntimeError):
    """Template tried to perform insecure operations in sandbox mode."""

class FilterArgumentError(TemplateRuntimeError):
    """Filter called with inappropriate arguments."""

class Undefined:
    """Default undefined type that raises errors on most operations."""

class StrictUndefined(Undefined):
    """Undefined that raises errors on any operation."""

class DebugUndefined(Undefined):
    """Undefined that shows debug info when printed."""

class ChainableUndefined(Undefined):
    """Undefined that doesn't raise on getattr/getitem operations."""
```