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'>, keep_lines=False, strict=False)[source]¶
Compile mustache template as a tuple of token tuples.
- Parameters:
template (
bytes) – template as utf-8 encoded bytestags (
tuple[bytes,bytes] |Sequence[bytes]) – mustache tag tuple (open, close)comments (
bool) – whether yield comment tokens or not (ignore comments)cache (
CompiledTemplateCache) – mutable mapping for compiled template cachecache_make_key (
Callable[[tuple[bytes,bytes,bytes,bool,bool,bool]],Any]) – key function for compiled template cachekeep_lines (
bool) – disable mustache tag-only-line collapsingstrict (
bool) – disable compatibility workarounds
- Return type:
- Returns:
tuple of token tuples
- Raises:
UnclosedSectionException – if section is left unclosed
UnopenedSectionException – if closing an invalid section
UnclosedTokenException – if tag is left unclosed
DelimiterTokenException – if delimiter token syntax is invalid
Added in version 0.3.0: keep_lines to disable tag-only-line collapsing, strict to disable compatability workarounds
- mstache.stream(template, scope, *, scopes=(), resolver=<function default_resolver>, getter=(<function default_getter>, <function default_strict_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, keep_lines=False, strict=False)[source]¶
Generate rendered mustache template chunks.
- Parameters:
template (
TypeVar(TString, bound=str|bytes)) – mustache template (str or bytes)scope (
Any) – current rendering scope (data object)scopes (
Iterable) – list of precedent scopesresolver (
Callable[[str|bytes],str|bytes|None]) – callable will be used to resolve partials (bytes)getter (
Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]] |tuple[Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]],Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]]] |Sequence[Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]]]) – callable will be used to pick variables from scopestringify (
Callable[[Any,bool],bytes]) – callable will be used to render python types (bytes)escape (
Callable[[bytes],bytes]) – callable will be used to escape template (bytes)lambda_render (
Callable[...,Callable[...,str|bytes]] |None) – explicit lambda render function constructortags (
tuple[str|bytes,str|bytes] |Sequence[str|bytes]) – tuple (start, end) specifying the initial mustache delimiterscache (
CompiledTemplateCache) – mutable mapping for compiled template cachecache_make_key (
Callable[[tuple[bytes,bytes,bytes,bool,bool,bool]],Any]) – key function for compiled template cacherecursion_limit (
int) – maximum number of nested render operationskeep_lines (
bool) – disable mustache tag-only-line collapsingstrict (
bool) – disable compatibility workarounds
- Return type:
- Returns:
generator of bytes/str chunks (type depends on template)
- Raises:
UnclosedSectionException – if section is left unclosed
UnopenedSectionException – if closing an invalid section
UnclosedTokenException – if tag is left unclosed
DelimiterTokenException – if delimiter token syntax is invalid
TemplateRecursionError – if rendering recursion limit is exceeded
Added in version 0.3.0: getter support for
mstache.PropertyGetterTuple, keep_lines to disable block-line stripping, strict to disable compatability workarounds
- mstache.render(template, scope, *, scopes=(), resolver=<function default_resolver>, getter=(<function default_getter>, <function default_strict_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, keep_lines=False, strict=False)[source]¶
Render mustache template.
- Parameters:
template (
TypeVar(TString, bound=str|bytes)) – mustache templatescope (
Any) – current rendering scope (data object)scopes (
Iterable) – list of precedent scopesresolver (
Callable[[str|bytes],str|bytes|None]) – callable will be used to resolve partials (bytes)getter (
Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]] |tuple[Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]],Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]]] |Sequence[Callable[[Any,Sequence,str|bytes,TypeVar(T)],Union[Any,TypeVar(T)]]]) – callable will be used to pick variables from scopestringify (
Callable[[Any,bool],bytes]) – callable will be used to render python types (bytes)escape (
Callable[[bytes],bytes]) – callable will be used to escape template (bytes)lambda_render (
Callable[...,Callable[...,str|bytes]] |None) – explicit lambda render function constructortags (
tuple[str|bytes,str|bytes] |Sequence[str|bytes]) – tuple (start, end) specifying the initial mustache delimiterscache (
CompiledTemplateCache) – mutable mapping for compiled template cachecache_make_key (
Callable[[tuple[bytes,bytes,bytes,bool,bool,bool]],Any]) – key function for compiled template cacherecursion_limit (
int) – maximum number of nested render operationskeep_lines (
bool) – disable mustache tag-only-line collapsingstrict (
bool) – disable compatibility workarounds
- Return type:
- Returns:
rendered bytes/str (type depends on template)
- Raises:
UnclosedSectionException – if section is left unclosed
UnopenedSectionException – if closing an invalid section
UnclosedTokenException – if tag is left unclosed
DelimiterTokenException – if delimiter token syntax is invalid
TemplateRecursionError – if rendering recursion limit is exceeded
Added in version 0.3.0: getter support for
mstache.PropertyGetterTuple, keep_lines to disable tag-only-line collapsing, strict to disable compatability workarounds
- mstache.cli(argv=None)[source]¶
Render template from command line.
Use
python -m mstache --helpto check available options.
- exception mstache.TokenException[source]¶
Bases:
SyntaxErrorInvalid token found during tokenization.
- mstache.ClosingTokenException¶
Deprecated since version 0.3.0: Use
SectionExceptioninstead.
- exception mstache.SectionException[source]¶
Bases:
TokenExceptionSection error found during tokenization.
Added in version 0.3.0.
- exception mstache.UnopenedSectionException[source]¶
Bases:
SectionExceptionClosing unknown section during tokenization.
Added in version 0.3.0.
- exception mstache.UnclosedSectionException[source]¶
Bases:
SectionExceptionSection left unclosed during tokenization.
Added in version 0.3.0.
- exception mstache.UnclosedTokenException[source]¶
Bases:
TokenExceptionToken left unclosed during tokenization.
- exception mstache.DelimiterTokenException[source]¶
Bases:
TokenExceptionInvalid delimiters token found during tokenization.
Added in version 0.1.1.
- exception mstache.TemplateRecursionError[source]¶
Bases:
RecursionErrorTemplate 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_getter(scope, scopes, key, default=None, *, virtuals=mappingproxy({'length': <function virtual_length>}))[source]¶
Extract property value from scope hierarchy retrying until full match.
- Parameters:
- Return type:
- Returns:
value from scope or default
Both
AttributeErrorandTypeErrorexceptions raised by virtual property implementations will be handled as if that property doesn’t exist, which can be useful to filter out incompatible types.Added in version 0.1.3: virtuals parameter.
- mstache.default_strict_getter(scope, scopes, key, default=None, *, virtuals=mappingproxy({'length': <function virtual_length>}))[source]¶
Extract property value from scope hierarchy retrying until partial match.
- Parameters:
- Return type:
- Returns:
value from scope or default
Both
AttributeErrorandTypeErrorexceptions raised by virtual property implementations will be handled as if that property doesn’t exist, which can be useful to filter out incompatible types.Added in version 0.3.0.
- mstache.default_getter_tuple = (<function default_getter>, <function default_strict_getter>)¶
Tuple with each getter function for compatibility and strict modes.
Items:
Reference to
default_getter()used in non-strict mode.Reference to
default_strict_getter()used in strict mode..
See also
default_getter()Default getter implementation referenced by this tuple.
Added in version 0.3.0.
- mstache.default_stringify(data, text)[source]¶
Convert arbitrary data to bytes.
- Parameters:
- Return type:
- Returns:
template bytes
Changed in version 0.3.0:
Noneto emit empty bytes
- mstache.default_escape(data)[source]¶
Convert bytes conflicting with HTML to their escape sequences.
- mstache.default_lambda_render(scope, **kwargs)[source]¶
Generate a template-only render function with fixed parameters.
- 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 intuple[bytes, bytes, bytes, bool]containing the relevantmstache.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).
- mstache.Buffer: TypeAlias = str | bytes¶
String/bytes, string or bytes depending on text or binary mode.
Added in version 0.3.0.
- class mstache.TString¶
String/bytes generic, string or bytes depending on text or binary mode.
- mstache.PartialResolver¶
Template partial resolver function interface.
See also
mstache.default_resolver()Default partial resolver stub implementation.
- mstache.PropertyGetter¶
Template property getter function interface.
See also
mstache.default_getter()Default non-strict getter implementation.
mstache.default_strict_getter()Default strict getter implementation.
- mstache.PropertyGetterTuple: TypeAlias = tuple[collections.abc.Callable[[typing.Any, collections.abc.Sequence, str | bytes, ~T], typing.Union[typing.Any, ~T]], collections.abc.Callable[[typing.Any, collections.abc.Sequence, str | bytes, ~T], typing.Union[typing.Any, ~T]]] | collections.abc.Sequence[collections.abc.Callable[[typing.Any, collections.abc.Sequence, str | bytes, ~T], typing.Union[typing.Any, ~T]]]¶
Tuple of property getter functions: non-strict and strict.
See also
mstache.PropertyGetterProperty getter function interface.
mstache.default_getter()Default non-strict getter implementation.
mstache.default_strict_getter()Default strict getter implementation.
- mstache.StringifyFunction¶
Template variable general stringification function interface.
See also
mstache.default_stringify()Default stringify-function implementation.
- mstache.EscapeFunction¶
Template variable value escape function interface.
- mstache.LambdaRenderFunctionConstructor: TypeAlias = collections.abc.Callable[..., collections.abc.Callable[..., str | bytes]] | None¶
Lambda render function constructor or
Nonefor implicit rendering.Options:
collections.abc.Callablereturning another callable which to be sent viarenderparameter to explicit (chevron-style) lambdas expecting both template content and render parameters.Noneenables implicit rendering of lambda return values (spec-style) with lambdas only receving the template content as argument.
See also
mstache.default_lambda_render()Default explicit lambda render constructor.
Changed in version 0.3.0:
Nonefor implicit return value render.
- mstache.VirtualPropertyFunction¶
Virtual property implementation callable interface.
- mstache.VirtualPropertyMapping¶
Virtual property mapping interface.
See also
mstache.default_virtualsDefault mapping of virtual property functions.
- mstache.TagsTuple: TypeAlias = tuple[str | bytes, str | bytes] | collections.abc.Sequence[str | bytes]¶
Mustache tag tuple interface.
See also
mstache.default_tagsDefault tuple of mustache template tags.
- mstache.TagsByteTuple: TypeAlias = tuple[bytes, bytes] | collections.abc.Sequence[bytes]¶
Mustache tag byte tuple interface.
See also
mstache.default_tagsDefault tuple of mustache template tags.
- mstache.CompiledToken¶
Compiled template token.
Tokens are tuples containing a renderer decision path, key, content and flags.
a: boolDecision for rendering path node
a.b: boolDecision for rendering path node
b.c: boolDecision for rendering path node
c.key: bytesTemplate substring with token scope key.
content: bytesTemplate substring with token content data.
flags: intToken flags.
Unused:
-1(default)- Variable flags:
0- escaped1- unescaped
- Block start flags:
0- falsy1- truthy
Block end value: block content index.
- mstache.CompiledTemplate¶
Compiled template interface.
See also
mstache.CompiledTokenItem type.
mstache.CompiledTemplateCacheInterface exposing this type.
alias of
tuple[tuple[bool,bool,bool,bytes,bytes,int], …]
- class mstache.CompiledTemplateCache(*args, **kwargs)[source]¶
Bases:
ProtocolCache object protocol.
See also
mstache.CompiledTemplateItem type.
mstache.CacheMakeKeyFunctionCache key function interface.
mstache.default_cacheDefault cache instance.