API reference

mstache module.

This module alone implements the entire mstache library, including its minimal command line interface.

The main functions are considered to be cli(), render() and stream(), and they expose different approaches to template rendering: command line interface, buffered and streaming rendering API, respectively.

Other functionality will be considered advanced, exposing some implementation-specific complexity and potentially non-standard behavior which could reduce compatibility with other mustache implementations and future major mstache revisions.

mstache.tokenize(template, *, tags=(b'{{', b'}}'), comments=False, cache={}, cache_make_key=<class 'tuple'>)[source]

Compile mustache template as a tuple of token tuples.

Parameters:
Return type:

tuple[tuple[bool, bool, bool, bytes, bytes, int], ...]

Returns:

tuple of token tuples

Raises:
mstache.stream(template, scope, *, scopes=(), resolver=<function default_resolver>, getter=<function default_getter>, stringify=<function default_stringify>, escape=<function default_escape>, lambda_render=<function default_lambda_render>, tags=(b'{{', b'}}'), cache={}, cache_make_key=<class 'tuple'>, recursion_limit=1024)[source]

Generate rendered mustache template chunks.

Parameters:
Return type:

Generator[TypeVar(TString, str, bytes), None, None]

Returns:

generator of bytes/str chunks (same type as template)

Raises:
mstache.render(template, scope, *, scopes=(), resolver=<function default_resolver>, getter=<function default_getter>, stringify=<function default_stringify>, escape=<function default_escape>, lambda_render=<function default_lambda_render>, tags=(b'{{', b'}}'), cache={}, cache_make_key=<class 'tuple'>, recursion_limit=1024)[source]

Render mustache template.

Parameters:
Return type:

TypeVar(TString, str, bytes)

Returns:

rendered bytes/str (type depends on template)

Raises:
mstache.cli(argv=None)[source]

Render template from command line.

Use python -m mstache –help to check available options.

Parameters:

argv (Sequence[str] | None) – command line arguments, sys.argv when None

Return type:

None

exception mstache.TokenException[source]

Bases: SyntaxError

Invalid token found during tokenization.

classmethod from_template(template, start, end)[source]

Create exception instance from parsing data.

Parameters:
  • template (bytes) – template bytes

  • start (int) – character position where the offending tag starts at

  • end (int) – character position where the offending tag ends at

Return type:

TokenException

Returns:

exception instance

exception mstache.ClosingTokenException[source]

Bases: TokenException

Non-matching closing token found during tokenization.

exception mstache.UnclosedTokenException[source]

Bases: ClosingTokenException

Unclosed token found during tokenization.

exception mstache.DelimiterTokenException[source]

Bases: TokenException

Invalid delimiters token found during tokenization.

Added in version 0.1.1.

exception mstache.TemplateRecursionError[source]

Bases: RecursionError

Template rendering exceeded maximum render recursion.

mstache.default_recursion_limit = 1024

Default number of maximum nested renders.

A nested render happens whenener the lambda render parameter is used or when a partial template is injected.

Meant to avoid recursion bombs on templates.

mstache.default_resolver(name)[source]

Mustache partial resolver function (stub).

Parameters:

name (AnyStr) – partial template name

Return type:

bytes

Returns:

empty bytes

mstache.default_getter(scope, scopes, key, default=None, *, virtuals=mappingproxy({'length': <function virtual_length>}))[source]

Extract property value from scope hierarchy.

Parameters:
  • scope (Any) – uppermost scope (corresponding to key '.')

  • scopes (Iterable) – parent scope sequence

  • key (AnyStr) – property key

  • default (Any) – value will be used as default when missing

  • virtuals (Mapping[str, Callable[[Any], Any]]) – mapping of virtual property callables

Return type:

Any

Returns:

value from scope or default

Added in version 0.1.3: virtuals parameter.

Both AttributeError and TypeError exceptions raised by virtual property implementations will be handled as if that property doesn’t exist, which can be useful to filter out incompatible types.

mstache.default_stringify(data, text)[source]

Convert arbitrary data to bytes.

Parameters:
  • data (Any) – value will be serialized

  • text (bool) – whether running in text mode or not (bytes mode)

Return type:

bytes

Returns:

template bytes

mstache.default_escape(data)[source]

Convert bytes conflicting with HTML to their escape sequences.

Parameters:

data (bytes) – bytes containing text

Return type:

bytes

Returns:

escaped text bytes

mstache.default_lambda_render(scope, **kwargs)[source]

Generate a template-only render function with fixed parameters.

Parameters:
  • scope (Any) – current scope

  • **kwargs – parameters forwarded to render()

Return type:

Callable[[TypeVar(TString, str, bytes)], TypeVar(TString, str, bytes)]

Returns:

template render function

mstache.default_tags = (b'{{', b'}}')

Tuple of default mustache tags as in tuple[bytes, bytes].

mstache.default_cache: CompiledTemplateCache = {}

Default template cache mapping, keeping the 1024 most recently used compiled templates (LRU expiration).

mstache.default_cache_make_key

Defaut template cache key function, tuple, so keys would be as in tuple[bytes, bytes, bytes, bool] containing the relevant mstache.tokenizer() parameters.

mstache.default_virtuals: Mapping[str, Callable[[Any], Any]] = mappingproxy({'length': <function virtual_length>})

Immutable mapping with default virtual properties.

The following virtual properties are implemented:

  • length, for non-mapping sized objects, returning len(ref).

class mstache.TString

String/bytes generic.

alias of TypeVar(‘TString’, str, bytes)

mstache.PartialResolver

Template partial tag resolver function interface.

alias of Callable

mstache.PropertyGetter

Template property getter function interface.

alias of Callable[Any, Sequence, AnyStr, Any, Any]

mstache.StringifyFunction

Template variable general stringification function interface.

alias of Callable[bytes, bool, bytes]

mstache.EscapeFunction

Template variable value escape function interface.

alias of Callable[bytes, bytes]

mstache.LambdaRenderFunctionConstructor

Lambda render function constructor interface.

alias of Callable[…, Callable[…, AnyStr]]

mstache.VirtualPropertyFunction

Virtual property implementation callable interface.

alias of Callable[Any, Any]

mstache.VirtualPropertyMapping

Virtual property mapping interface.

alias of Mapping[str, Callable[Any, Any]]

mstache.TagsTuple

Mustache tag tuple interface.

alias of tuple[AnyStr, AnyStr]

mstache.TagsByteTuple

Mustache tag byte tuple interface.

alias of tuple[bytes, bytes]

mstache.CompiledToken

Compiled template token.

Tokens are tuples containing a renderer decision path, key, content and flags.

type: bool

Decision for rendering path node a.

type: bool

Decision for rendering path node b.

type: bool

Decision for rendering path node c

key: bytes

Template substring with token scope key.

``content: bytes`

Template substring with token content data.

flags: int

Token flags.

  • Unused: -1 (default)

  • Variable flags:
    • 0 - escaped

    • 1 - unescaped

  • Block start flags:
    • 0 - falsy

    • 1 - truthy

  • Block end value: block content index.

alias of tuple[bool, bool, bool, bytes, bytes, int]

mstache.CompiledTemplate

Compiled template interface.

See also

mstache.CompiledToken

Item type.

mstache.CompiledTemplateCache

Interface exposing this type.

alias of tuple[tuple[bool, bool, bool, bytes, bytes, int], …]

class mstache.CompiledTemplateCache(*args, **kwargs)[source]

Bases: Protocol

Cache object protocol.

See also

mstache.CompiledTemplate

Item type.

mstache.CacheMakeKeyFunction

Cache key function interface.

get(key)[source]

Get compiled template from key, if any.

Return type:

tuple[tuple[bool, bool, bool, bytes, bytes, int], ...] | None

mstache.CacheMakeKeyFunction

Cache mapping key function interface.

See also

mstache.CompiledTemplateCache

Interface exposing this type.

alias of Callable[[tuple[bytes, bytes, bytes, bool]], Hashable]