API reference

ustache module.

This module alone implements the entire ustache 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 implentations and future major ustache versions.

ustache.tokenize(template, *, tags=(b'{{', b'}}'), comments=False, cache={}, cache_hasher=<function default_cache_hasher>)[source]

Compile mustache template as a tuple of token tuples.

Parameters
Return type

Tuple[Tuple[bool, bool, bool, slice, slice, int], …]

Returns

tuple of token tuples

Raises
ustache.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_hasher=<function default_cache_hasher>)[source]

Generate rendered mustache template chunks.

Parameters
Return type

Generator[~TString, None, None]

Returns

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

Raises
ustache.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_hasher=<function default_cache_hasher>)[source]

Render mustache template.

Parameters
Return type

~TString

Returns

rendered bytes/str (type depends on template)

Raises
ustache.cli(argv=None)[source]

Render template from command line.

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

Parameters

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

Return type

None

exception ustache.TokenException[source]

Bases: SyntaxError

Invalid token found during tokenization.

message = 'Invalid tag {tag} at line {row} column {column}'
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 ustache.ClosingTokenException[source]

Bases: ustache.TokenException

Non-matching closing token found during tokenization.

message = 'Non-matching tag {tag} at line {row} column {column}'
exception ustache.UnclosedTokenException[source]

Bases: ustache.ClosingTokenException

Unclosed token found during tokenization.

message = 'Unclosed tag {tag} at line {row} column {column}'
exception ustache.DelimiterTokenException[source]

Bases: ustache.TokenException

Invalid delimiters token found during tokenization.

New in version 0.1.1.

message = 'Invalid delimiters {tag} at line {row} column {column}'
ustache.default_resolver(name)[source]

Mustache partial resolver function (stub).

Parameters

name (AnyStr) – partial template name

Return type

bytes

Returns

empty bytes

ustache.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 (Sequence[Any]) – parent scope sequence

  • key (AnyStr) – property key

  • default (Optional[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

New 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.

ustache.default_stringify(data, text=False)[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

ustache.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

ustache.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[[~TString], ~TString]

Returns

template render function

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

Tuple of default mustache tags (in bytes).

ustache.default_cache: MutableMapping[Tuple[Hashable, bytes, bytes, bool], Tuple[Tuple[bool, bool, bool, slice, slice, int], ...]] = {}

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

ustache.default_cache_hasher(template)[source]

Calculate a template hash.

The resulting hash is based on both zlib.crc32() and template size, effectively using more than 32 bits to minimize chance of collisions.

Parameters

template (bytes) – template data as bytes

Return type

int

Returns

template hash as integer

ustache.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).

ustache.TString

String/bytes generic.

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

ustache.PartialResolver

Template partial tag resolver function interface.

alias of Callable

ustache.PropertyGetter

Template property getter function interface.

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

ustache.StringifyFunction

Template variable general stringification function interface.

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

ustache.EscapeFunction

Template variable value escape function interface.

alias of Callable[[bytes], bytes]

ustache.LambdaRenderFunctionFactory

Deprecated since version 0.1.3: Use LambdaRenderFunctionConstructor instead.

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

ustache.LambdaRenderFunctionConstructor

Lambda render function constructor interface.

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

ustache.CompiledTemplate

Compiled template interface.

See also

ustache.CompiledToken

Item type.

ustache.CompiledTemplateCache

Interface exposing this type.

alias of Tuple[Tuple[bool, bool, bool, slice, slice, int], …]

ustache.CompiledToken

Compiled template token.

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

type: bool

Decission for rendering path node a.

type: bool

Decission for rendering path node b.

type: bool

Decission for rendering path node c

key: Optional[slice]

Template slice for token scope key, if any.

content: Optional[slice]

Template slice for token content data, if any.

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, slice, slice, int]

ustache.CompiledTemplateCache

Cache mapping interface.

See also

ustache.CompiledTemplateCache

Item type.

alias of MutableMapping[Tuple[Hashable, bytes, bytes, bool], Tuple[Tuple[bool, bool, bool, slice, slice, int], …]]

ustache.TagsTuple

Mustache tag tuple interface.

alias of Tuple