Sanic API

The Sanic integration provides a replacement for Sanic’s template rendering that supports block-level rendering.

API Reference

async jinja2_fragments.sanic.render(template_name='', status=200, headers=None, content_type='text/html; charset=utf-8', app=None, environment=None, context=None, *, block=None, blocks=None)[source]

Render a template or specific blocks within a template using Sanic.

This function renders a complete template or specific block(s) from a given template. It supports both synchronous and asynchronous rendering based on the application’s configuration. If neither block nor blocks is provided, the entire template is rendered.

Parameters:
  • template_name (str) – The name of the template to be rendered.

  • status (int) – The HTTP status code to be returned with the response.

  • headers (Optional[Dict[str, str]]) – A dictionary of HTTP headers to include in the response.

  • content_type (str) – The content type of the HTTP response.

  • app (Optional[Sanic]) – The Sanic application instance. If omitted, attempts to locate the current app automatically.

  • environment (Optional[Environment]) – The Jinja2 environment used for templating.

  • context (Optional[Dict[str, Any]]) – A dictionary containing variables to be passed to the template or blocks for rendering.

  • block (Optional[str]) – The name of the single block to render within the template.

  • blocks (Optional[list[str]]) – A list of block names to render within the template. Only one of block or blocks can be set.

Return type:

TemplateResponse

Returns:

A Sanic TemplateResponse containing the rendered content.

Raises:
  • ValueError – If both block and blocks are set.

  • SanicException – If the Sanic application cannot be determined automatically.

  • ExtensionNotFound – If the templating extension is not enabled or Jinja2 is not installed.