class litestar.response.template.Template#

Bases: Response[bytes]

Template-based response, rendering a given template into a bytes string.

__init__(template_name: str | None = None, *, template_str: str | None = None, background: BackgroundTask | BackgroundTasks | None = None, context: dict[str, Any] | None = None, cookies: ResponseCookies | None = None, encoding: str = 'utf-8', headers: dict[str, Any] | None = None, media_type: MediaType | str | None = None, status_code: int = 200) None#

Handle the rendering of a given template into a bytes string.

  • template_name – Path-like name for the template to be rendered, e.g. index.html.

  • template_str – A string representing the template, e.g. tmpl = "Hello <strong>World</strong>".

  • background – A BackgroundTask instance or BackgroundTasks to execute after the response is finished. Defaults to None.

  • context – A dictionary of key/value pairs to be passed to the temple engine’s render method.

  • cookies – A list of Cookie instances to be set under the response Set-Cookie header.

  • encoding – Content encoding

  • headers – A string keyed dictionary of response headers. Header keys are insensitive.

  • media_type – A string or member of the MediaType enum. If not set, try to infer the media type based on the template name. If this fails, fall back to text/plain.

  • status_code – A value for the response HTTP status code.

create_template_context(request: Request) dict[str, Any]#

Create a context object for the template.


request – A Request instance.


A dictionary holding the template context

to_asgi_response(app: Litestar | None, request: Request, *, background: BackgroundTask | BackgroundTasks | None = None, cookies: Iterable[Cookie] | None = None, encoded_headers: Iterable[tuple[bytes, bytes]] | None = None, headers: dict[str, str] | None = None, is_head_response: bool = False, media_type: MediaType | str | None = None, status_code: int | None = None, type_encoders: TypeEncodersMap | None = None) ASGIResponse#

Create an ASGIResponse from a Response instance.

  • app – The Litestar application instance.

  • background – Background task(s) to be executed after the response is sent.

  • cookies – A list of cookies to be set on the response.

  • encoded_headers – A list of already encoded headers.

  • headers – Additional headers to be merged with the response headers. Response headers take precedence.

  • is_head_response – Whether the response is a HEAD response.

  • media_type – Media type for the response. If media_type is already set on the response, this is ignored.

  • request – The Request instance.

  • status_code – Status code for the response. If status_code is already set on the response, this is

  • type_encoders – A dictionary of type encoders to use for encoding the response content.


An ASGIResponse instance.