Module

rendering.engines.kida

Kida template engine integration for Bengal.

Implements TemplateEngineProtocol for Kida, making it available as a BYOR (Bring Your Own Renderer) option.

Configuration:

template_engine: kida

Features:

  • 2-5x faster than Jinja2 for typical templates
  • Free-threading safe (Python 3.14t)
  • Native async support
  • Pythonic scoping with let/set/export

Classes

KidaTemplateEngine 29
Bengal integration for Kida template engine. Implements TemplateEngineProtocol for seamless integr…

Bengal integration for Kida template engine.

Implements TemplateEngineProtocol for seamless integration with Bengal's rendering pipeline.

Methods

capabilities 0 EngineCapability
Return Kida engine capabilities. Kida supports all advanced features: - Block …
property
def capabilities(self) -> EngineCapability

Return Kida engine capabilities.

Kida supports all advanced features:

  • Block caching for efficient re-rendering
  • Block-level change detection for incremental builds
  • Template introspection for dependency analysis
  • Pipeline operators (|>) for functional transformations
  • Pattern matching (match/case) in templates
Returns
EngineCapability
env 0 Environment
Access to underlying Kida environment. Used by autodoc and other internals tha…
property
def env(self) -> Environment

Access to underlying Kida environment.

Used by autodoc and other internals that check template existence.

Returns
Environment
invalidate_menu_cache 0
Invalidate the menu dict cache. Call this after menus are rebuilt to ensure fr…
def invalidate_menu_cache(self) -> None

Invalidate the menu dict cache.

Call this after menus are rebuilt to ensure fresh dicts are generated. This ensures active menu states are correct for each page render.

render_template 2 str
Render a named template.
def render_template(self, name: str, context: dict[str, Any]) -> str
Parameters
Name Type Description
name

Template identifier (e.g., "blog/single.html")

context

Variables available to the template

Returns
str Rendered HTML string
render_string 3 str
Render a template string.
def render_string(self, template: str, context: dict[str, Any], *, strict: bool = True) -> str
Parameters
Name Type Description
template

Template content as string

context

Variables available to the template

strict

If False, return empty string for undefined variables instead of raising

Default:True
Returns
str Rendered HTML string
template_exists 1 bool
Check if a template exists.
def template_exists(self, name: str) -> bool
Parameters
Name Type Description
name

Template identifier

Returns
bool True if template can be loaded
get_template_path 1 Path | None
Resolve template name to filesystem path.
def get_template_path(self, name: str) -> Path | None
Parameters
Name Type Description
name

Template identifier

Returns
Path | None Absolute path to template, or None if not found
list_templates 0 list[str]
List all available template names.
def list_templates(self) -> list[str]
Returns
list[str] Sorted list of template names
validate 1 list[TemplateError]
Validate templates for syntax errors.
def validate(self, patterns: list[str] | None = None) -> list[TemplateError]
Parameters
Name Type Description
patterns

Optional glob patterns to filter

Default:None
Returns
list[TemplateError] List of TemplateError for invalid templates
has_capability 1 bool
Check if Kida has a specific capability.
def has_capability(self, cap: EngineCapability) -> bool
Parameters
Name Type Description
cap
Returns
bool
get_template_introspection 1 dict[str, Any] | None
Get introspection metadata for a template. **Returns analysis of template stru…
def get_template_introspection(self, name: str) -> dict[str, Any] | None

Get introspection metadata for a template.

Returns analysis of template structure including:

  • blocks: Block metadata (dependencies, purity, cache scope)
  • extends: Parent template name (if any)
  • all_dependencies: All context paths the template accesses
Parameters
Name Type Description
name

Template identifier (e.g., "page.html")

Returns
dict[str, Any] | None Dict with template metadata, or None if: - Template not found - AST was not preserved (preserve_ast=False)
get_cacheable_blocks 1 dict[str, str]
Get blocks that can be cached and their cache scope. Convenience method for bu…
def get_cacheable_blocks(self, name: str) -> dict[str, str]

Get blocks that can be cached and their cache scope.

Convenience method for build optimization. Returns only blocks with determined cache scope (excludes "unknown").

Parameters
Name Type Description
name

Template identifier

Returns
dict[str, str] Dict of block_name → cache_scope ("site" or "page")
render 2 str
Alias for render_template (for compatibility).
def render(self, template_name: str, context: dict[str, Any]) -> str
Parameters
Name Type Description
template_name
context
Returns
str
validate_templates 1 list[TemplateError]
Alias for validate (for compatibility).
def validate_templates(self, include_patterns: list[str] | None = None) -> list[TemplateError]
Parameters
Name Type Description
include_patterns Default:None
Returns
list[TemplateError]
get_template_profile 0 dict[str, Any] | None
Get template profiling report.
def get_template_profile(self) -> dict[str, Any] | None
Returns
dict[str, Any] | None Dictionary with timing statistics, or None if profiling disabled.
clear_template_cache 1
Clear template cache for external invalidation. Called by TemplateChangeDetect…
def clear_template_cache(self, names: list[str] | None = None) -> None

Clear template cache for external invalidation.

Called by TemplateChangeDetector when template files change to force cache invalidation without waiting for hash checks.

Parameters
Name Type Description
names

Optional list of template names to clear. If None, clears all cached templates.

Default:None
precompile_templates 1 int
Pre-compile templates to warm the cache. Compiles templates ahead of rendering…
def precompile_templates(self, template_names: list[str] | None = None) -> int

Pre-compile templates to warm the cache.

Compiles templates ahead of rendering to avoid compile-on-demand overhead during the render phase. This is especially beneficial when using bytecode caching (templates are compiled and cached to disk).

Parameters
Name Type Description
template_names

Optional list of template names to precompile. If None, precompiles all templates in template_dirs.

Default:None
Returns
int Number of templates compiled
cache_info 0 dict[str, Any]
Get cache statistics for monitoring.
def cache_info(self) -> dict[str, Any]
Returns
dict[str, Any] Dict with template, fragment, and bytecode cache stats
Internal Methods 11
__init__ 2
Initialize Kida engine for site. **Bytecode Cache:** When enabled, compiled te…
def __init__(self, site: Site, *, profile: bool = False)

Initialize Kida engine for site.

Bytecode Cache: When enabled, compiled template bytecode is persisted to .bengal/cache/kida/for near-instant cold-start loading. Provides 90%+ improvement in template loading times.

Parameters
Name Type Description
site

Bengal Site instance

profile

Enable template profiling for performance analysis

Default:False
_build_template_dirs 0 list[Path]
Build ordered list of template search directories. Uses same resolution logic …
def _build_template_dirs(self) -> list[Path]

Build ordered list of template search directories.

Uses same resolution logic as Jinja engine:

  1. Site-level custom templates (highest priority)
  2. Theme chain (child themes first, then parent themes)
Returns
list[Path]
_select_autoescape 1 bool
Determine autoescape based on file extension.
def _select_autoescape(self, name: str | None) -> bool
Parameters
Name Type Description
name
Returns
bool
_register_bengal_template_functions 0
Register Bengal-specific template functions. Strategy: 1. Apply shared engine …
def _register_bengal_template_functions(self) -> None

Register Bengal-specific template functions.

Strategy:

  1. Apply shared engine globals via get_engine_globals()
  2. Use register_all() with engine_type="kida" for filters and non-context functions
  3. Add engine-specific globals (url_for, get_menu, breadcrumbs)

This uses the centralized context layer for consistent globals across engines.

_get_menu 1 list[dict]
Get menu items as dicts (cached).
def _get_menu(self, menu_name: str = 'main') -> list[dict]
Parameters
Name Type Description
menu_name Default:'main'
Returns
list[dict]
_get_menu_lang 2 list[dict]
Get menu items for a specific language (cached).
def _get_menu_lang(self, menu_name: str = 'main', lang: str = '') -> list[dict]
Parameters
Name Type Description
menu_name Default:'main'
lang Default:''
Returns
list[dict]
_url_for 1 str
Generate URL for a page with base URL support.
def _url_for(self, page: Any) -> str
Parameters
Name Type Description
page
Returns
str
_track_referenced_templates 1
Track all referenced templates (extends/includes/imports) as dependencies. Rec…
def _track_referenced_templates(self, template_name: str) -> None

Track all referenced templates (extends/includes/imports) as dependencies.

Recursively walks the template tree to find all templates that could affect the output. Tracks:

  • Parent templates ({% extends %})
  • Included templates ({% include %})
  • Imported templates ({% import %}, {% from ... import %})
Parameters
Name Type Description
template_name

Name of template to analyze

_extract_referenced_templates 1 set[str]
Extract all referenced template names from an AST. Walks the AST to find Exten…
def _extract_referenced_templates(self, ast: Any) -> set[str]

Extract all referenced template names from an AST.

Walks the AST to find Extends, Include, Import, and FromImport nodes and extracts their template names (if static strings).

Parameters
Name Type Description
ast

Parsed template AST

Returns
set[str] Set of template names referenced by this template
_find_template_path 1 Path | None
Alias for get_template_path (used by debug/explainer).
def _find_template_path(self, name: str) -> Path | None
Parameters
Name Type Description
name
Returns
Path | None
_resolve_theme_chain 1 list[str]
Resolve theme inheritance chain.
def _resolve_theme_chain(self, active_theme: str | None) -> list[str]
Parameters
Name Type Description
active_theme
Returns
list[str]

Functions

_check_protocol 0 None
Verify KidaTemplateEngine implements TemplateEngineProtocol.
def _check_protocol() -> None