class litestar.template.TemplateEngineProtocol#

Bases: Protocol[TemplateType_co, ContextType_co]

Protocol for template engines.

__init__(directory: Path | list[Path] | None, engine_instance: Any | None) None#

Initialize the template engine with a directory.

  • directory – Direct path or list of directory paths from which to serve templates, if provided the implementation has to create the engine instance.

  • engine_instance – A template engine object, if provided the implementation has to use it.

get_template(template_name: str) TemplateType_co#

Retrieve a template by matching its name (dotted path) with files in the directory or directories provided.


template_name – A dotted path


Template instance


TemplateNotFoundException – if no template is found.

render_string(template_string: str, context: Mapping[str, Any]) str#

Render a template from a string with the given context.

  • template_string – The template string to render.

  • context – A dictionary of variables to pass to the template.


The rendered template as a string.

register_template_callable(key: str, template_callable: Callable[[Concatenate[ContextType_co, P]], R]) None#

Register a callable on the template engine.

  • key – The callable key, i.e. the value to use inside the template to call the callable.

  • template_callable – A callable to register.



class litestar.template.TemplateProtocol#

Bases: Protocol

Protocol Defining a Template.

Template is a class that has a render method which renders the template into a string.

render(*args: Any, **kwargs: Any) str#

Return the rendered template as a string.

  • *args – Positional arguments passed to the TemplateEngine

  • **kwargs – A string keyed mapping of values passed to the TemplateEngine


The rendered template string

__init__(*args, **kwargs)#
class litestar.template.TemplateConfig#

Bases: Generic[EngineType]

Configuration for Templating.

To enable templating, pass an instance of this class to the Litestar constructor using the ‘template_config’ key.

engine: type[EngineType] | EngineType | None = None#

A template engine adhering to the TemplateEngineProtocol.

directory: PathType | list[PathType] | None = None#

A directory or list of directories from which to serve templates.

engine_callback: Callable[[EngineType], None] | None = None#

A callback function that allows modifying the instantiated templating protocol.

__init__(engine: type[EngineType] | EngineType | None = None, directory: PathType | list[PathType] | None = None, engine_callback: Callable[[EngineType], None] | None = None, instance: EngineType | None = None) None#
instance: EngineType | None = None#

An instance of the templating protocol.

__post_init__() None#

Ensure that directory is set if engine is a class.

to_engine() EngineType#

Instantiate the template engine.

property engine_instance: EngineType#

Return the template engine instance.