minijinja

    A port of MiniJinja (a Jinja2 template engine) to MoonBit

    template
    jinja
    jinja2
    minijinja
    Download zip
    Author
    Version
    0.1.0
    License
    Apache-2.0
    Last updated
    8 hours ago
    Downloads
    1

    Dependencies

    #minijinja.mbt

    A port of MiniJinja — a powerful but minimal dependency template engine based on the syntax and behavior of the Jinja2 template engine for Python — to MoonBit.

    The port follows the upstream implementation closely: the same lexer, parser, bytecode compiler and VM, the same value model, filters, tests and functions. It passes all of upstream's lexer, parser, compiler and template snapshot tests (see docs/PLAN.md for the details of the port).

    The library is pure MoonBit and works on all backends (native, wasm, wasm-gc and js).

    #Example

    ///|
    test "hello world" {
    let env = @minijinja.Environment::new()
    env.add_template("hello.txt", "Hello {{ name }}!")
    let tmpl = env.get_template("hello.txt")
    let ctx = @minijinja.Value::from_pairs([
    ("name", @minijinja.Value::from_string("John")),
    ])
    inspect(tmpl.render(ctx), content="Hello John!")
    }

    #Template inheritance, macros and loops

    ///|
    test "inheritance" {
    let env = @minijinja.Environment::new()
    env.add_template(
    "layout.html", "<title>{% block title %}{% endblock %}</title>{% block body %}{% endblock %}",
    )
    env.add_template(
    "index.html",
    (
    #|{% extends "layout.html" %}
    #|{% macro item(x) %}<li>{{ x }}</li>{% endmacro %}
    #|{% block title %}Items{% endblock %}
    #|{% block body %}<ul>{% for x in items %}{{ item(x) }}{% endfor %}</ul>{% endblock %}
    ),
    )
    let ctx = @minijinja.Value::from_pairs([
    (
    "items",
    @minijinja.Value::from_array([
    @minijinja.Value::from_string("<a>"),
    @minijinja.Value::from_int(42),
    ]),
    ),
    ])
    inspect(
    env.get_template("index.html").render(ctx),
    content="<title>Items</title><ul><li>&lt;a&gt;</li><li>42</li></ul>",
    )
    }

    HTML auto escaping is enabled for templates ending in .html, .htm and .xml (.json, .js and .yaml use JSON escaping).

    #Custom filters, tests and functions

    Filters, tests and functions are functions taking the render [State] and the arguments. The [Args] helper implements MiniJinja's argument conversion rules (missing and superfluous arguments, optional values, keyword arguments):

    ///|
    test "custom filter" {
    let env = @minijinja.Environment::new()
    env.add_filter("repeat", (state, args) => {
    let a = @minijinja.Args::new(state, args)
    let kwargs = a.kwargs()
    let value = a.string()
    let times = a.opt_usize().unwrap_or(2)
    let sep = kwargs.get_str("sep").unwrap_or("")
    a.finish()
    kwargs.assert_all_used()
    @minijinja.Value::from_string(Array::make(times, value).join(sep))
    })
    inspect(
    env.render_str(
    "{{ 'ab'|repeat }} {{ 'x'|repeat(3, sep='-') }}",
    @minijinja.Value::none(),
    ),
    content="abab x-x-x",
    )
    }

    Arguments can also be converted with the generic Args::next, which works for every type implementing FromValue (Bool, Int, Int64, Double, String, Value, Array[T] and T?):

    ///|
    test "typed arguments" {
    let env = @minijinja.Environment::new()
    env.add_function("clamp", (state, args) => {
    let a = @minijinja.Args::new(state, args)
    let value : Int = a.next()
    let lo : Int = a.next()
    let hi : Int? = a.next()
    a.finish()
    let hi = hi.unwrap_or(100)
    @minijinja.Value::from_int(
    if value < lo {
    lo
    } else if value > hi {
    hi
    } else {
    value
    },
    )
    })
    inspect(
    env.render_str(
    "{{ clamp(5, 10) }} {{ clamp(500, 1) }}",
    @minijinja.Value::none(),
    ),
    content="10 100",
    )
    }

    #Loaders, captured state and streaming

    Templates can be loaded on demand with a loader callback. Rendering can stream into a callback, and the final state can be used to render individual blocks or call macros:

    ///|
    test "loader and blocks" {
    let env = @minijinja.Environment::new()
    let sources = {
    "macros.txt": "{% macro hello(name) %}Hello {{ name }}!{% endmacro %}",
    "page.txt": "{% from 'macros.txt' import hello %}{% block title %}{{ hello(who) }}{% endblock %}",
    }
    env.set_loader(name => sources.get(name))
    let tmpl = env.get_template("page.txt")
    let ctx = @minijinja.Value::from_pairs([
    ("who", @minijinja.Value::from_string("World")),
    ])
    let out = StringBuilder()
    let state = tmpl.render_to(ctx, s => out.write_view(s))
    inspect(out.to_string(), content="Hello World!")
    inspect(state.render_block("title"), content="Hello World!")
    inspect(
    state.call_macro("hello", [@minijinja.Value::from_string("Moon")]),
    content="Hello Moon!",
    )
    }

    #Dynamic objects

    Implement the [Object] trait to expose your own types to templates:

    ///|
    struct Point {
    x : Int
    y : Int
    }

    ///|
    impl @minijinja.Object for Point with fn get_value(self, key) {
    match key.as_str() {
    Some("x") => Some(@minijinja.Value::from_int(self.x))
    Some("y") => Some(@minijinja.Value::from_int(self.y))
    _ => None
    }
    }

    ///|
    impl @minijinja.Object for Point with fn enumerate(_self) {
    Str(["x", "y"])
    }

    ///|
    test "objects" {
    let env = @minijinja.Environment::new()
    let ctx = @minijinja.Value::from_pairs([
    ("p", @minijinja.Value::from_object(Point::{ x: 1, y: 2, })),
    ])
    inspect(
    env.render_str("{{ p.x }},{{ p.y }} {{ p|list }}", ctx),
    content="1,2 ['x', 'y']",
    )
    }

    #Expressions

    ///|
    test "expressions" {
    let env = @minijinja.Environment::new()
    let expr = env.compile_expression("number < 42 and name is defined")
    let ctx = @minijinja.Value::from_pairs([
    ("number", @minijinja.Value::from_int(23)),
    ("name", @minijinja.Value::from_string("x")),
    ])
    inspect(expr.eval(ctx), content="True")
    }

    #Errors

    Errors carry the kind, a detail message and the location. When the debug mode is enabled (the default), errors raised during rendering also carry the template source and the referenced variables:

    ///|
    test "errors" {
    let env = @minijinja.Environment::new()
    env.add_template("bad.txt", "{{ [1, 2] + 23 }}")
    let tmpl = env.get_template("bad.txt")
    try tmpl.render(@minijinja.Value::none()) catch {
    err => {
    inspect(err.kind() == InvalidOperation, content="true")
    inspect(
    err,
    content="invalid operation: tried to use + operator on unsupported types sequence and number (in bad.txt:1)",
    )
    }
    } noraise {
    _ => fail("expected an error")
    }
    }

    #Differences to MiniJinja

    • Values are built with constructors (Value::from_string, from_int, from_array, from_pairs, from_json_str, ...) instead of From and serde.
    • Maps keep their insertion order (like the preserve_order feature).
    • Spans and TemplateError::range use UTF-16 offsets (lines and columns match upstream).
    • AutoEscape::None is called AutoEscape::NoEscape, ValueKind::None is ValueKind::Null.
    • Not ported: the datetime feature of minijinja-contrib, and parts of the CLI (see below).

    #Contrib

    The contrib package ports minijinja-contrib: Python compatibility methods (unknown_method_callback), extra filters (pluralize, filesizeformat, truncate, striptags, wordcount, wordwrap, random) and globals (cycler, joiner, randrange, lipsum). See contrib/README.mbt.md.

    #Command line tool

    cmd/minijinja ports minijinja-cli (the logic lives in the testable cli package, @cli.run). It runs on the native and wasm backends and does its I/O through moonbitlang/async:

    moon run cmd/minijinja -- hello.j2 hello.json moon run cmd/minijinja -- --template='Hello {{ name }}!' -Dname=World moon run cmd/minijinja -- --expr '1 + 1' moon run cmd/minijinja -- --help

    All options of the upstream tool are supported except the ones listed below, with the same semantics, error messages and exit codes (2 for usage errors, 1 for failures, the result for --expr-out=status): -f/--format, -a/--autoescape, -D/--define, --strict, --no-include, --safe-path, --fuel, -n/--no-newline, --trim-blocks, --lstrip-blocks, --py-compat, -s/--syntax, --env, -t/--template, -E/--expr, --expr-out, --dump, -o/--output, --select, --help, --long-help, --syntax-help, -V/--version and the MINIJINJA_* environment variables. Contrib filters and globals are always enabled.

    Not ported: the yaml, toml, cbor, ini and json5 data formats (only json and querystring are available), the TOML config file (--config-file, --print-config), --repl and --generate-completion. Template paths are normalized lexically instead of being canonicalized.

    #License

    Apache-2.0, like the original project. MiniJinja is © Armin Ronacher.

    FormatterFunc

    type FormatterFunc = (Output, State, Value) -> Unit raise TemplateError

    A callback that formats a value to the output.

    NativeFunction

    type NativeFunction = (State, Array[Value]) -> Value raise TemplateError

    The signature of filters, tests and functions.

    FromValue

    pub(open) trait FromValue {
    fn from_value(Value?) -> Self raise TemplateError
    }

    Conversion from template values into MoonBit values.

    This mirrors MiniJinja's ArgType: from_value receives None when the argument is missing. Implementations exist for the common primitive types, Value, Array[T] and T? (where undefined and none map to None).
    impl FromValue for Bool
    impl FromValue for Int
    impl FromValue for Int64
    impl FromValue for UInt64
    impl FromValue for Double
    impl FromValue for String
    impl FromValue for Option[T]
    impl FromValue for Array[T]

    Object

    pub(open) trait Object {
    fn repr(Self) -> ObjectRepr = _
    fn get_value(Self, Value) -> Value? = _
    fn get_value_by_str(Self, String) -> Value? = _
    fn enumerate(Self) -> Enumerator = _
    fn enumerator_len(Self) -> Int? = _
    fn is_true(Self) -> Bool = _
    fn call(Self, State, Array[Value]) -> Value raise TemplateError = _
    fn call_method(Self, State, String, Array[Value]) -> Value raise TemplateError = _
    fn render(Self) -> String? = _
    fn custom_cmp(Self, Value) -> Int? = _
    }

    A trait that represents a dynamic object.

    Implement this trait for your own types to expose them to templates via [Value::from_object]. Every method has a default implementation, so only the relevant ones need to be provided.

    • repr defaults to [ObjectRepr::Map].
    • get_value defaults to None (undefined).
    • enumerate defaults to an empty enumerator for maps, sequences and iterables and to [Enumerator::NonEnumerable] for plain objects.
    • call and call_method fail by default.
    • render returns None to request the default rendering.
    • custom_cmp returns None to use the default comparison. When it is implemented it is consulted for equality and ordering against any other object (it should return None for objects it does not understand).

    TemplateError

    pub suberror TemplateError {
    TemplateError(ErrorData)
    }

    Represents template errors.

    Errors carry a [ErrorKind], an optional detail message, and — once the engine knows about it — the name of the template and the location in it.

    TemplateError::debug_string

    fn TemplateError::debug_string(self : TemplateError, pretty? : Bool) -> String

    Formats the error like Rust's Debug ({:?} or {:#?} when pretty is set). This does not include the debug info.

    TemplateError::detail

    fn TemplateError::detail(self : TemplateError) -> String?

    Returns the error detail.

    TemplateError::display_debug_info

    fn TemplateError::display_debug_info(self : TemplateError) -> String

    Renders only the debug info section of the error.

    TemplateError::display_with_debug_info

    fn TemplateError::display_with_debug_info(self : TemplateError) -> String

    Formats the error like Rust's alternate Display ({:#}) which includes the debug info (template source excerpt and referenced variables).

    TemplateError::from_kind

    fn TemplateError::from_kind(kind : ErrorKind) -> TemplateError

    Creates a new error with just a kind.

    TemplateError::kind

    Returns the error kind.

    TemplateError::line

    fn TemplateError::line(self : TemplateError) -> Int?

    Returns the line number where the error occurred.

    TemplateError::name

    fn TemplateError::name(self : TemplateError) -> String?

    Returns the filename of the template that caused the error.

    TemplateError::new

    fn TemplateError::new(kind : ErrorKind, detail : String) -> TemplateError

    Creates a new error with a kind and a detail message.

    TemplateError::range

    fn TemplateError::range(self : TemplateError) -> (Int, Int)?

    Returns the byte range of where the error occurred if available. In MoonBit the offsets are UTF-16 code unit offsets into the source.

    TemplateError::source

    Returns the source error if there is one.

    TemplateError::span

    fn TemplateError::span(self : TemplateError) -> Span?

    Returns the span of the error in the template source, if known.

    TemplateError::template_source

    fn TemplateError::template_source(self : TemplateError) -> String?

    Returns the template source if available.

    TemplateError::to_string

    fn TemplateError::to_string(self : TemplateError) -> String

    Formats the error like Rust's Display ({}).

    TemplateError::with_source

    fn TemplateError::with_source(self : TemplateError, source : TemplateError) -> TemplateError

    Attaches another error as source to this error.

    Args

    pub struct Args {
    // private fields
    }

    A cursor over the arguments passed to a filter, test or function.

    The conversion rules follow MiniJinja's argument conversion: missing required arguments raise MissingArgument, leftover arguments raise TooManyArguments in [Args::finish], optional arguments treat undefined and none as missing, and keyword arguments (if accepted) have to be extracted first with [Args::kwargs].

    Args::bool

    fn Args::bool(self : Args) -> Bool raise TemplateError

    A required boolean argument.

    Args::f64

    fn Args::f64(self : Args) -> Double raise TemplateError

    A required float argument.

    Args::finish

    fn Args::finish(self : Args) -> Unit raise TemplateError

    Ensures that all arguments were consumed.

    Args::has_more

    fn Args::has_more(self : Args) -> Bool

    Returns true if there are positional arguments left.

    Args::i32

    fn Args::i32(self : Args) -> Int raise TemplateError

    A required 32 bit integer argument.

    Args::i64

    fn Args::i64(self : Args) -> Int64 raise TemplateError

    A required 64 bit integer argument.

    Args::kwargs

    fn Args::kwargs(self : Args) -> Kwargs

    Extracts the trailing keyword arguments. Must be called before any positional argument is read.

    Args::new

    fn Args::new(state : State, values : Array[Value]) -> Args

    Creates an argument cursor.

    Args::next

    fn[T : FromValue] Args::next(self : Args) -> T raise TemplateError

    Reads the next positional argument converted to T.

    test {
    let env = @minijinja.Environment::new()
    env.add_function("add", (state, args) => {
    let a = @minijinja.Args::new(state, args)
    let x : Int = a.next()
    let y : Int? = a.next()
    a.finish()
    @minijinja.Value::from_int(x + y.unwrap_or(1))
    })
    inspect(
    env.render_str("{{ add(1) }} {{ add(1, 2) }}", @minijinja.Value::none()),
    content="2 3",
    )
    }

    Args::opt_bool

    fn Args::opt_bool(self : Args) -> Bool? raise TemplateError

    An optional boolean argument.

    Args::opt_i32

    fn Args::opt_i32(self : Args) -> Int? raise TemplateError

    An optional 32 bit integer argument.

    Args::opt_i64

    fn Args::opt_i64(self : Args) -> Int64? raise TemplateError

    An optional 64 bit integer argument.

    Args::opt_str

    fn Args::opt_str(self : Args) -> String? raise TemplateError

    An optional strict string argument.

    Args::opt_string

    fn Args::opt_string(self : Args) -> String? raise TemplateError

    An optional string argument (the value is converted to a string).

    Args::opt_string_input

    fn Args::opt_string_input(self : Args) -> StringInput? raise TemplateError

    An optional string argument that retains safety provenance.

    Args::opt_usize

    fn Args::opt_usize(self : Args) -> Int? raise TemplateError

    An optional non-negative integer argument.

    Args::opt_value

    fn Args::opt_value(self : Args) -> Value? raise TemplateError

    An optional argument of any type.

    Args::rest

    fn Args::rest(self : Args) -> Array[Value] raise TemplateError

    All remaining positional arguments (keyword arguments are rejected).

    Args::rest_with_kwargs

    fn Args::rest_with_kwargs(self : Args) -> Array[Value]

    All remaining arguments including keyword arguments.

    Args::str

    fn Args::str(self : Args) -> String raise TemplateError

    A required strict string argument (must be a string value).

    Args::string

    fn Args::string(self : Args) -> String raise TemplateError

    A required string argument (the value is converted to a string).

    Args::string_input

    fn Args::string_input(self : Args) -> StringInput raise TemplateError

    A required string argument that retains safety provenance.

    Args::usize

    fn Args::usize(self : Args) -> Int raise TemplateError

    A required non-negative integer argument.

    Args::value

    fn Args::value(self : Args) -> Value raise TemplateError

    A required argument of any type (keyword arguments are rejected).

    Args::value_or_kwargs

    fn Args::value_or_kwargs(self : Args) -> Value raise TemplateError

    A required argument that may also be keyword arguments.

    AutoEscape

    pub(all) enum AutoEscape {
    NoEscape
    Html
    Json
    Custom(String)
    } derive(Eq)

    Controls the autoescaping behavior.

    Captured

    pub struct Captured {
    output : String
    state : State
    }

    Captured render output together with the state.

    DynObject

    pub struct DynObject {
    // private fields
    }

    A type erased object. Values hold objects through this handle which carries a stable identity.

    DynObject::call

    fn DynObject::call(self : DynObject, state : State, args : Array[Value]) -> Value raise TemplateError

    Calls the object.

    DynObject::call_method

    fn DynObject::call_method(self : DynObject, state : State, name : String, args : Array[Value]) -> Value raise TemplateError

    Calls a method on the object.

    DynObject::enumerate

    fn DynObject::enumerate(self : DynObject) -> Enumerator

    Returns the enumerator of the object.

    DynObject::enumerator_len

    fn DynObject::enumerator_len(self : DynObject) -> Int?

    Returns the length of the enumerator if known.

    DynObject::get_value

    fn DynObject::get_value(self : DynObject, key : Value) -> Value?

    Looks up an item (or attribute) on the object.

    DynObject::get_value_by_str

    fn DynObject::get_value_by_str(self : DynObject, key : String) -> Value?

    Looks up an attribute by a string key.

    DynObject::is_same_object

    fn DynObject::is_same_object(self : DynObject, other : DynObject) -> Bool

    Returns true if both handles point to the same object.

    DynObject::is_true

    fn DynObject::is_true(self : DynObject) -> Bool

    Returns the truthiness of the object.

    DynObject::repr

    fn DynObject::repr(self : DynObject) -> ObjectRepr

    Returns the representation of the object.

    DynObject::try_iter

    fn DynObject::try_iter(self : DynObject) -> Iter[Value]?

    Returns an iterator over the values of the object if it is enumerable.

    DynObject::try_iter_pairs

    fn DynObject::try_iter_pairs(self : DynObject) -> Iter[(Value, Value)]?

    Returns an iterator over the key/value pairs of the object. For sequences the keys are the indexes.

    Enumerator

    pub(all) enum Enumerator {
    NonEnumerable
    Empty
    Str(Array[String])
    Iter(Iter[Value])
    KeyValueIter(Iter[(Value, Value)])
    Seq(Int)
    Values(Array[Value])
    }

    Enumerators help define iteration behavior for [Object]s.

    When Jinja wants to know the length of an object, if it's empty or not or if it wants to iterate over it, it will ask the object for an enumerator.

    Environment

    pub struct Environment {
    // private fields
    }

    An abstraction that holds the engine configuration.

    This object holds the central configuration state for templates. It is also the container for all loaded templates.

    There are generally two ways to construct an environment:

    • [Environment::new] creates an environment preconfigured with sensible defaults. It will contain all built-in filters, tests and globals as well as a callback for auto escaping based on file extension.
    • [Environment::empty] creates a completely blank environment.

    Environment::add_filter

    fn Environment::add_filter(self : Environment, name : String, f : (State, Array[Value]) -> Value raise TemplateError) -> Unit

    Adds a new filter function.

    Filter functions are functions that can be applied to values in templates. The first argument is the value the filter is applied to.

    Environment::add_function

    fn Environment::add_function(self : Environment, name : String, f : (State, Array[Value]) -> Value raise TemplateError) -> Unit

    Adds a new global function.

    Environment::add_global

    fn Environment::add_global(self : Environment, name : String, value : Value) -> Unit

    Adds a global variable.

    Environment::add_template

    fn Environment::add_template(self : Environment, name : String, source : String) -> Unit raise TemplateError

    Loads a template from a string into the environment.

    The name parameter defines the name of the template which identifies it. To look up a loaded template use the [get_template] method.

    Environment::add_test

    fn Environment::add_test(self : Environment, name : String, f : (State, Array[Value]) -> Value raise TemplateError) -> Unit

    Adds a new test function.

    Test functions are similar to filters but perform a check on a value where the return value is always considered a boolean.

    Environment::clear_templates

    fn Environment::clear_templates(self : Environment) -> Unit

    Removes all stored templates.

    Environment::clone

    fn Environment::clone(self : Environment) -> Environment

    Creates a copy of the environment. Templates, filters, tests and globals added to the copy do not affect the original and vice versa.

    Environment::compile_expression

    fn Environment::compile_expression(self : Environment, expr : String) -> Expression raise TemplateError

    Compiles an expression.

    This lets one compile an expression in the template language and receive the output. This lets one use the expressions of the language be used as a minimal scripting language.

    Environment::debug

    fn Environment::debug(self : Environment) -> Bool

    Returns the current value of the debug flag.

    Environment::empty

    fn Environment::empty() -> Environment

    Creates a completely empty environment.

    This environment has no filters, no templates, no globals and no default logic for auto escaping configured.

    Environment::empty_state

    fn Environment::empty_state(self : Environment) -> State

    Returns an empty [State] for testing purposes and similar.

    Environment::fuel

    fn Environment::fuel(self : Environment) -> Int64?

    Returns the configured fuel.

    Environment::get_template

    fn Environment::get_template(self : Environment, name : String) -> Template raise TemplateError

    Fetches a template by name.

    This requires that the template has been loaded with add_template beforehand or that a loader can produce it.

    Environment::globals

    fn Environment::globals(self : Environment) -> Array[(String, Value)]

    Returns all globals as name/value pairs (sorted by name).

    Environment::keep_trailing_newline

    fn Environment::keep_trailing_newline(self : Environment) -> Bool

    Returns the value of the trailing newline preservation flag.

    Environment::lstrip_blocks

    fn Environment::lstrip_blocks(self : Environment) -> Bool

    Returns the value of the lstrip blocks flag.

    Environment::new

    Creates a new environment with sensible defaults.

    This environment does not yet contain any templates but it will have all the default filters, tests and globals loaded. If you do not want any default configuration you can use [Environment::empty].

    Environment::recursion_limit

    fn Environment::recursion_limit(self : Environment) -> Int

    Returns the current max recursion limit.

    Environment::remove_filter

    fn Environment::remove_filter(self : Environment, name : String) -> Unit

    Removes a filter by name.

    Environment::remove_global

    fn Environment::remove_global(self : Environment, name : String) -> Unit

    Removes a global function or variable by name.

    Environment::remove_template

    fn Environment::remove_template(self : Environment, name : String) -> Unit

    Removes a template by name.

    Environment::remove_test

    fn Environment::remove_test(self : Environment, name : String) -> Unit

    Removes a test by name.

    Environment::render_named_str

    fn Environment::render_named_str(self : Environment, name : String, source : String, ctx : Value) -> String raise TemplateError

    Parses and renders a template from a string in one go with name.

    Environment::render_str

    fn Environment::render_str(self : Environment, source : String, ctx : Value) -> String raise TemplateError

    Parses and renders a template from a string in one go.

    test {
    let env = @minijinja.Environment::new()
    let ctx = @minijinja.Value::from_pairs([
    ("name", @minijinja.Value::from_string("World")),
    ])
    inspect(env.render_str("Hello {{ name }}!", ctx), content="Hello World!")
    }

    Environment::set_auto_escape_callback

    fn Environment::set_auto_escape_callback(self : Environment, f : (String) -> AutoEscape) -> Unit

    Sets a new function to select the default auto escaping.

    This function is invoked when templates are loaded into the environment to determine the default auto escaping behavior. The function is invoked with the name of the template.

    Environment::set_debug

    fn Environment::set_debug(self : Environment, enabled : Bool) -> Unit

    Enable or disable the debug mode.

    When the debug mode is enabled the engine will dump out some of the execution state together with the source information of the executing template when an error is created.

    Environment::set_formatter

    fn Environment::set_formatter(self : Environment, f : (Output, State, Value) -> Unit raise TemplateError) -> Unit

    Sets a different formatter function.

    The formatter is invoked to format the given value into the provided output. The default formatter escapes values according to the auto escape flag of the state.

    Environment::set_fuel

    fn Environment::set_fuel(self : Environment, fuel : Int64?) -> Unit

    Sets the optional fuel of the engine.

    When MiniJinja is compiled with fuel support (always the case in this port), the engine will consume fuel on every instruction it executes. Once the engine runs out of fuel, rendering fails with an OutOfFuel error. This can be used to limit the amount of work a template can do.

    Environment::set_keep_trailing_newline

    fn Environment::set_keep_trailing_newline(self : Environment, yes : Bool) -> Unit

    Preserve the trailing newline when rendering templates.

    Environment::set_loader

    fn Environment::set_loader(self : Environment, f : (String) -> String? raise TemplateError) -> Unit

    Registers a template loader as source of templates.

    When a template loader is registered, the environment gains the ability to dynamically load templates. The loader is invoked with the name of the template. If this template exists Some(source) has to be returned, otherwise None. Once a template has been loaded it's stored on the environment.

    Environment::set_lstrip_blocks

    fn Environment::set_lstrip_blocks(self : Environment, yes : Bool) -> Unit

    Remove leading spaces and tabs from the start of a line to a block.

    Environment::set_path_join_callback

    fn Environment::set_path_join_callback(self : Environment, f : (String, String) -> String) -> Unit

    Sets a callback to join template paths (for relative includes).

    The callback is invoked with the name of the template to load and the name of the template that is loading it.

    Environment::set_recursion_limit

    fn Environment::set_recursion_limit(self : Environment, level : Int) -> Unit

    Reconfigures the runtime recursion limit (capped at 500).

    Environment::set_syntax

    fn Environment::set_syntax(self : Environment, syntax : SyntaxConfig) -> Unit

    Sets the syntax for the environment.

    Note that this only affects templates that are added after the syntax was changed.

    Environment::set_trim_blocks

    fn Environment::set_trim_blocks(self : Environment, yes : Bool) -> Unit

    Remove the first newline after a block.

    Environment::set_undefined_behavior

    fn Environment::set_undefined_behavior(self : Environment, behavior : UndefinedBehavior) -> Unit

    Changes the undefined behavior.

    Environment::set_unknown_method_callback

    fn Environment::set_unknown_method_callback(self : Environment, f : (State, Value, String, Array[Value]) -> Value raise TemplateError) -> Unit

    Sets a callback invoked when an unknown method is called on an object.

    Environment::syntax

    fn Environment::syntax(self : Environment) -> SyntaxConfig

    Returns the current syntax config.

    Environment::template_from_named_str

    fn Environment::template_from_named_str(self : Environment, name : String, source : String) -> Template raise TemplateError

    Loads a template from a string, with name.

    In some cases you really only need a template to be compiled once. This creates a template that is not stored on the environment.

    Environment::template_from_str

    fn Environment::template_from_str(self : Environment, source : String) -> Template raise TemplateError

    Loads a template from a string (named <string>).

    Environment::template_names

    fn Environment::template_names(self : Environment) -> Array[String]

    Returns the names of all loaded templates.

    Environment::templates

    fn Environment::templates(self : Environment) -> Array[(String, Template)]

    Returns all loaded templates (sorted by name).

    Environment::trim_blocks

    fn Environment::trim_blocks(self : Environment) -> Bool

    Returns the value of the trim blocks flag.

    Environment::undefined_behavior

    fn Environment::undefined_behavior(self : Environment) -> UndefinedBehavior

    Returns the current undefined behavior.

    ErrorData

    type ErrorData

    ErrorKind

    pub(all) enum ErrorKind {
    NonPrimitive
    NonKey
    InvalidOperation
    SyntaxError
    TemplateNotFound
    TooManyArguments
    MissingArgument
    UnknownFilter
    UnknownTest
    UnknownFunction
    UnknownMethod
    BadEscape
    UndefinedError
    BadSerialization
    CannotDeserialize
    BadInclude
    EvalBlock
    CannotUnpack
    WriteFailure
    OutOfFuel
    InvalidDelimiter
    UnknownBlock
    } derive(Eq, Hash,
    Debug
    )

    An enum describing the error kind.
    impl Show for ErrorKind

    ErrorKind::description

    fn ErrorKind::description(self : ErrorKind) -> String

    A short human readable description of the kind.

    ErrorKind::name

    fn ErrorKind::name(self : ErrorKind) -> String

    The name of the kind as Rust's Debug would print it.

    Expression

    pub struct Expression {
    // private fields
    }

    A handle to a compiled expression.

    An expression is created via the [Environment::compile_expression] method. It provides a method to evaluate the expression and return the result as value object.

    Expression::eval

    fn Expression::eval(self : Expression, ctx : Value) -> Value raise TemplateError

    Evaluates the expression with some context.

    test {
    let env = @minijinja.Environment::new()
    let expr = env.compile_expression("number < 42")
    let ctx = @minijinja.Value::from_pairs([
    ("number", @minijinja.Value::from_int(23)),
    ])
    inspect(expr.eval(ctx).to_string(), content="True")
    }

    Expression::undeclared_variables

    fn Expression::undeclared_variables(self : Expression, nested? : Bool) -> Array[String]

    Returns a set of all undeclared variables in the expression.

    ExtensionKey

    pub struct ExtensionKey[T] {
    // private fields
    }

    A typed key for per-render [State] extensions.

    Extensions let filters and functions keep their own state for the duration of a render (for instance a random number generator or a cache). Create one key per kind of extension (typically as a toplevel let).

    test {
    let counter : @minijinja.ExtensionKey[Ref[Int]] = @minijinja.ExtensionKey::new()
    let env = @minijinja.Environment::new()
    env.add_function("count", (state, _args) => {
    let c = state.get_or_insert_extension(counter, () => { val: 0, })
    c.val 1
    @minijinja.Value::from_int(c.val)
    })
    inspect(
    env.render_str(
    "{{ count() }}{{ count() }}{{ count() }}",
    @minijinja.Value::none(),
    ),
    content="123",
    )
    inspect(
    env.render_str("{{ count() }}", @minijinja.Value::none()),
    content="1",
    )
    }

    ExtensionKey::new

    fn[T] ExtensionKey::new() -> ExtensionKey[T]

    Creates a new, unique extension key.

    FormatStyle

    pub(all) enum FormatStyle {
    Printf
    StrFormat
    } derive(Eq)

    The supported format string styles.

    Kwargs

    pub struct Kwargs {
    // private fields
    }

    Keyword arguments passed to a filter, test or function.

    Keyword arguments are represented as a special map value which is passed as the last argument. Use [Args::kwargs] to extract them, then fetch individual arguments with [Kwargs::get] (or the typed getters) and finally call [Kwargs::assert_all_used] so that unknown keyword arguments are reported.

    Kwargs::args

    fn Kwargs::args(self : Kwargs) -> Array[String]

    Returns the names of all passed keyword arguments.

    Kwargs::assert_all_used

    fn Kwargs::assert_all_used(self : Kwargs) -> Unit raise TemplateError

    Asserts that all kwargs were used.

    Kwargs::from_pairs

    fn Kwargs::from_pairs(pairs : Array[(String, Value)]) -> Kwargs

    Creates keyword arguments from name/value pairs.

    Kwargs::get

    fn Kwargs::get(self : Kwargs, key : String) -> Value raise TemplateError

    Gets a required keyword argument (any value) and marks it as used.

    Kwargs::get_as

    fn[T : FromValue] Kwargs::get_as(self : Kwargs, key : String) -> T raise TemplateError

    Reads a keyword argument converted to T and marks it used. Missing keyword arguments raise unless T is an option.

    Kwargs::get_bool

    fn Kwargs::get_bool(self : Kwargs, key : String) -> Bool? raise TemplateError

    Gets an optional boolean keyword argument.

    Kwargs::get_int

    fn Kwargs::get_int(self : Kwargs, key : String) -> Int64? raise TemplateError

    Gets an optional integer keyword argument.

    Kwargs::get_opt

    fn Kwargs::get_opt(self : Kwargs, key : String) -> Value? raise TemplateError

    Gets an optional keyword argument and marks it as used. Undefined and none values are treated as missing (like Option<Value>).

    Kwargs::get_str

    fn Kwargs::get_str(self : Kwargs, key : String) -> String? raise TemplateError

    Gets an optional string keyword argument (strict: must be a string).

    Kwargs::get_usize

    fn Kwargs::get_usize(self : Kwargs, key : String) -> Int? raise TemplateError

    Gets an optional non-negative integer keyword argument.

    Kwargs::has

    fn Kwargs::has(self : Kwargs, key : String) -> Bool

    Checks if a keyword argument exists.

    Kwargs::peek

    fn Kwargs::peek(self : Kwargs, key : String) -> Value?

    Returns the raw value of a keyword argument without marking it used.

    Kwargs::to_value

    fn Kwargs::to_value(self : Kwargs) -> Value

    Converts the keyword arguments back into a value.

    ObjectRepr

    pub(all) enum ObjectRepr {
    Plain
    Map
    Seq
    Iterable
    } derive(Compare, Eq,
    Debug
    )

    Defines the natural representation of an object.

    An [ObjectRepr] is a reduced form of [ValueKind] which only contains value types that can be represented by objects.

    Output

    pub struct Output {
    // private fields
    }

    An abstraction over output targets with support for capturing.

    Captures nest: begin_capture starts a new capture (or a discarding capture) and end_capture returns what was captured as a value.

    Output::write_char

    fn Output::write_char(self : Output, c : Char) -> Unit raise TemplateError

    Writes a character to the output.

    Output::write_str

    fn Output::write_str(self : Output, s : StringView) -> Unit raise TemplateError

    Writes a string to the output.

    Span

    pub(all) struct Span {
    start_line : Int
    start_col : Int
    start_offset : Int
    end_line : Int
    end_col : Int
    end_offset : Int
    } derive(Eq)

    Token span information.

    Lines start at 1 and columns at 0; both are counted in Unicode scalar values like in MiniJinja. Offsets are UTF-16 code unit offsets into the template source.
    impl Default for Span
    impl Show for Span

    Span::default

    fn Span::default() -> Span

    Returns an empty span (all positions zero).

    Span::to_string

    fn Span::to_string(self : Span) -> String

    Formats the span like MiniJinja's Debug for Span ( @ 1:0-1:5).

    State

    pub struct State {
    // private fields
    }

    Provides access to the current execution state of the engine.

    A read only reference is passed to filter functions and similar objects to allow limited interfacing with the engine.

    State::apply_filter

    fn State::apply_filter(self : State, filter : String, args : Array[Value]) -> Value raise TemplateError

    Invokes a filter with some arguments.

    State::auto_escape

    fn State::auto_escape(self : State) -> AutoEscape

    Returns the current value of the auto escape flag.

    State::call_macro

    fn State::call_macro(self : State, name : String, args : Array[Value]) -> String raise TemplateError

    Invokes a macro by name with the given arguments.

    State::current_block

    fn State::current_block(self : State) -> String?

    Returns the name of the innermost block.

    State::env

    fn State::env(self : State) -> Environment

    Returns a reference to the current environment.

    State::exports

    fn State::exports(self : State) -> Array[String]

    Returns a list of the names of all exports (top-level variables).

    State::format

    fn State::format(self : State, value : Value) -> String raise TemplateError

    Formats a value to a string using the formatter on the environment.

    State::fuel_levels

    fn State::fuel_levels(self : State) -> (Int64, Int64)?

    Returns the amount of fuel consumed and remaining (if fuel is enabled).

    State::get_extension

    fn[T] State::get_extension(self : State, key : ExtensionKey[T]) -> T?

    Returns the extension value stored for key, if any.

    State::get_or_insert_extension

    fn[T] State::get_or_insert_extension(self : State, key : ExtensionKey[T], make : () -> T) -> T

    Returns the extension value for key, inserting make() if missing.

    State::get_temp

    fn State::get_temp(self : State, name : String) -> Value?

    Looks up a temp and returns it.

    State::get_template

    fn State::get_template(self : State, name : String) -> Template raise TemplateError

    Fetches a template by name with path joining.

    State::known_variables

    fn State::known_variables(self : State) -> Array[String]

    Returns a list of all known variables.

    State::lookup

    fn State::lookup(self : State, name : String) -> Value?

    Looks up a variable by name in the context.

    State::name

    fn State::name(self : State) -> String

    Returns the name of the current template.

    State::perform_test

    fn State::perform_test(self : State, test_name : String, args : Array[Value]) -> Bool raise TemplateError

    Invokes a test function on a value.

    State::render_block

    fn State::render_block(self : State, block : String) -> String raise TemplateError

    Renders a block with the given name into a string.

    This method works like [Template::render] but it only renders a specific block in the template.

    State::render_block_to

    fn State::render_block_to(self : State, block : String, write : (StringView) -> Unit raise) -> Unit raise TemplateError

    Renders a block with the given name, streaming the output into write.

    State::set_extension

    fn[T] State::set_extension(self : State, key : ExtensionKey[T], value : T) -> Unit

    Stores an extension value on the state (replacing an existing one).

    State::set_temp

    fn State::set_temp(self : State, name : String, value : Value) -> Value?

    Inserts a temp and returns the old temp.

    State::undefined_behavior

    fn State::undefined_behavior(self : State) -> UndefinedBehavior

    Returns the current undefined behavior.

    StringInput

    pub struct StringInput {
    // private fields
    }

    A string coerced from a value together with its safety provenance.

    StringInput::as_str

    fn StringInput::as_str(self : StringInput) -> String

    Returns the coerced string.

    StringInput::format

    fn StringInput::format(self : StringInput, state : State) -> String raise TemplateError

    Formats the string for insertion into a safe result. Safe inputs are returned unchanged, other inputs are escaped like the escape filter.

    StringInput::is_safe

    fn StringInput::is_safe(self : StringInput) -> Bool

    Returns true if the original value was marked safe.

    StringInput::new

    fn StringInput::new(state : State, value : Value) -> StringInput raise TemplateError

    Coerces a value into a string while retaining its safety provenance.

    StringInput::preserve_safety

    fn StringInput::preserve_safety(self : StringInput, value : String) -> Value

    Wraps a derived string while preserving the input's safety.

    SyntaxConfig

    pub struct SyntaxConfig {
    // private fields
    }

    The delimiter configuration for the environment and the parser.

    MiniJinja allows you to override the syntax configuration for templates by setting different delimiters. The end markers can be shared, but the start markers need to be distinct. It would thus not be valid to configure {{ to be the marker for both variables and blocks.

    SyntaxConfig::block_delimiters

    fn SyntaxConfig::block_delimiters(self : SyntaxConfig) -> (String, String)

    Returns the block delimiters.

    SyntaxConfig::comment_delimiters

    fn SyntaxConfig::comment_delimiters(self : SyntaxConfig) -> (String, String)

    Returns the comment delimiters.

    SyntaxConfig::default

    fn SyntaxConfig::default() -> SyntaxConfig

    Returns the default syntax configuration ({% %}, {{ }}, {# #}).

    SyntaxConfig::line_comment_prefix

    fn SyntaxConfig::line_comment_prefix(self : SyntaxConfig) -> String?

    Returns the line comment prefix if set.

    SyntaxConfig::line_statement_prefix

    fn SyntaxConfig::line_statement_prefix(self : SyntaxConfig) -> String?

    Returns the line statement prefix if set.

    SyntaxConfig::new

    fn SyntaxConfig::new(block_delimiters? : (String, String), variable_delimiters? : (String, String), comment_delimiters? : (String, String), line_statement_prefix? : String, line_comment_prefix? : String) -> SyntaxConfig raise TemplateError

    Creates a new syntax configuration with custom delimiters.

    Delimiters are given as (start, end) pairs. Line statement and line comment prefixes are disabled unless given. Raises InvalidDelimiter if the start delimiters are not distinct.

    SyntaxConfig::variable_delimiters

    fn SyntaxConfig::variable_delimiters(self : SyntaxConfig) -> (String, String)

    Returns the variable delimiters.

    Template

    pub struct Template {
    // private fields
    }

    Represents a handle to a template.

    Templates are stored in the [Environment] as bytecode instructions. With the [Environment::get_template] method that is looked up and returned in form of this handle. Such a template can be rendered with [Template::render].

    Template::debug_instructions

    fn Template::debug_instructions(self : Template) -> Array[(String, Array[String])]

    Returns the Debug representation of the compiled instructions of the template: one entry per block (sorted by block name) followed by the root instructions under the name <root>.

    This mirrors upstream's machinery::get_compiled_template and is meant for debugging tools such as the CLI's --dump=instructions.

    Template::name

    fn Template::name(self : Template) -> String

    Returns the name of the template.

    Template::new_state

    fn Template::new_state(self : Template) -> State

    Creates an empty [State] for this template.

    Template::render

    fn Template::render(self : Template, ctx : Value) -> String raise TemplateError

    Renders the template into a string.

    The provided value is used as the initial context for the template. It can be any object that implements the object protocol, typically a map created with [Value::from_pairs] or [Value::from_map].

    Template::render_captured

    fn Template::render_captured(self : Template, ctx : Value) -> Captured raise TemplateError

    Renders the template and returns the output together with the final state. The state can be used to render blocks or call macros.

    Template::render_to

    fn Template::render_to(self : Template, ctx : Value, write : (StringView) -> Unit raise) -> State raise TemplateError

    Renders the template, streaming the output into write.

    Errors raised by write abort rendering with a WriteFailure error. The final state is returned (like [Template::render_captured]).

    Template::source

    fn Template::source(self : Template) -> String

    Returns the source code of the template.

    Template::undeclared_variables

    fn Template::undeclared_variables(self : Template, nested? : Bool) -> Array[String]

    Returns a set of all undeclared variables in the template.

    This returns a set of all variables that might be looked up at runtime by the template. With nested set to true, attribute lookups on undeclared variables are tracked as dotted paths (foo.bar).

    UndefinedBehavior

    pub(all) enum UndefinedBehavior {
    Lenient
    Chainable
    SemiStrict
    Strict
    } derive(Eq)

    Defines the behavior of undefined values in the engine.

    Value

    type Value

    Represents a dynamically typed value in the template engine.
    impl FromValue for Value
    impl Compare for Value
    impl Eq for Value
    impl Hash for Value
    impl Show for Value

    Value::as_bigint

    Returns the value as a big integer if it is an integer (or an integral float). Covers the full 128 bit range.

    Value::as_bool

    fn Value::as_bool(self : Value) -> Bool?

    Returns the boolean if the value is a boolean (no truthiness check).

    Value::as_bytes

    fn Value::as_bytes(self : Value) -> Bytes?

    If the value is bytes (or a string), return the UTF-8 bytes.

    Value::as_f64

    fn Value::as_f64(self : Value) -> Double?

    Returns the value as Double if it is a number (or a bool).

    Value::as_i64

    fn Value::as_i64(self : Value) -> Int64?

    Returns the value as Int64 if it is an integer (or an integral float) that fits.

    Value::as_object

    fn Value::as_object(self : Value) -> DynObject?

    Returns the object handle if the value is an object.

    Value::as_str

    fn Value::as_str(self : Value) -> String?

    If the value is a string, return it. Bytes are returned if they are valid UTF-8.

    Value::as_uint64

    fn Value::as_uint64(self : Value) -> UInt64?

    Returns the value as UInt64 if it is a non-negative integer (or an integral float) that fits.

    Value::as_usize

    fn Value::as_usize(self : Value) -> Int?

    Returns the value as a non-negative Int index if possible.

    Value::call

    fn Value::call(self : Value, state : State, args : Array[Value]) -> Value raise TemplateError

    Calls the value directly.

    Value::call_method

    fn Value::call_method(self : Value, state : State, name : String, args : Array[Value]) -> Value raise TemplateError

    Calls a method on the value.

    Value::cmp

    fn Value::cmp(self : Value, other : Value) -> Int

    Compares two values like MiniJinja's Ord implementation.

    Value::convert

    fn[T : FromValue] Value::convert(self : Value) -> T raise TemplateError

    Converts a value into T.

    Value::debug_string

    fn Value::debug_string(self : Value, pretty? : Bool) -> String

    Formats the value like MiniJinja's Debug (a Python like repr).

    Value::from_array

    fn Value::from_array(items : Array[Value]) -> Value

    Creates a sequence value from an array.

    Value::from_bigint

    Creates a value from a big integer.

    Like Rust's Value::from(i128) / Value::from(u128) the value is stored as a 128 bit integer (signed if it fits, unsigned otherwise). Values outside of the 128 bit range become invalid values.

    Value::from_bool

    fn Value::from_bool(b : Bool) -> Value

    Value::from_bytes

    fn Value::from_bytes(b : Bytes) -> Value

    Value::from_char

    fn Value::from_char(c : Char) -> Value

    Value::from_double

    fn Value::from_double(f : Double) -> Value

    Value::from_dyn_object

    fn Value::from_dyn_object(obj : DynObject) -> Value

    Creates a value from a dynamic object handle.

    Value::from_error

    fn Value::from_error(err : TemplateError) -> Value

    Creates a value from an error. The value is invalid and raises the error as soon as it is used by the engine.

    Value::from_function

    fn Value::from_function(name : String, func : (State, Array[Value]) -> Value raise TemplateError) -> Value

    Creates a callable value from a function.

    Value::from_int

    fn Value::from_int(i : Int) -> Value

    Value::from_int64

    fn Value::from_int64(i : Int64) -> Value

    Value::from_json

    fn Value::from_json(j : Json) -> Value

    Converts a MoonBit Json value into a value.

    Value::from_json_str

    fn Value::from_json_str(s : String, sort_keys? : Bool) -> Value raise TemplateError

    Parses a JSON document into a value.

    Unlike @json.parse this preserves the distinction between integers (4) and floats (4.0). With sort_keys set, object keys are sorted (this matches the behavior of serde_json without preserve_order).

    Value::from_map

    fn Value::from_map(m : Map[Value, Value]) -> Value

    Creates a map value.

    Value::from_object

    fn[T : Object] Value::from_object(obj : T) -> Value

    Creates a value from a dynamic object.

    Value::from_pairs

    fn Value::from_pairs(pairs : Array[(String, Value)]) -> Value

    Creates a map value from key/value pairs.

    Value::from_safe_string

    fn Value::from_safe_string(s : String) -> Value

    Creates a value from a safe string.

    A safe string is one that will bypass auto escaping.

    Value::from_str_map

    fn Value::from_str_map(m : Map[String, Value]) -> Value

    Creates a map value from string keys.

    Value::from_string

    fn Value::from_string(s : String) -> Value

    Value::from_tuple

    fn Value::from_tuple(items : Array[Value]) -> Value

    Creates a tuple value.

    Value::from_uint64

    fn Value::from_uint64(i : UInt64) -> Value

    Value::get_attr

    fn Value::get_attr(self : Value, key : String) -> Value raise TemplateError

    Looks up an attribute by attribute name.

    This this returns undefined if an item does not exist, but it raises an error if the value itself is undefined.

    Value::get_item

    fn Value::get_item(self : Value, key : Value) -> Value raise TemplateError

    Looks up an item (or attribute) by key.

    This returns undefined if the item does not exist but raises an error if the value itself is undefined.

    Value::get_item_by_index

    fn Value::get_item_by_index(self : Value, idx : Int) -> Value raise TemplateError

    Looks up an index of the value.

    Value::is_integer

    fn Value::is_integer(self : Value) -> Bool

    Returns true if the value is an integer.

    Value::is_kwargs

    fn Value::is_kwargs(self : Value) -> Bool

    Returns true if the map represents keyword arguments.

    Value::is_none

    fn Value::is_none(self : Value) -> Bool

    Returns true if this value is none.

    Value::is_number

    fn Value::is_number(self : Value) -> Bool

    Returns true if the value is a number.

    Value::is_safe

    fn Value::is_safe(self : Value) -> Bool

    Returns true if this value is safe.

    Value::is_true

    fn Value::is_true(self : Value) -> Bool

    Is this value considered true?

    Value::is_tuple

    fn Value::is_tuple(self : Value) -> Bool

    Returns true if the value is a tuple.

    Value::is_undefined

    fn Value::is_undefined(self : Value) -> Bool

    Returns true if this value is undefined.

    Value::kind

    fn Value::kind(self : Value) -> ValueKind

    Returns the kind of the value.

    Value::len

    fn Value::len(self : Value) -> Int?

    Returns the length of the contained value.

    Strings return the number of Unicode scalar values, bytes the number of bytes and objects the length of their enumerator (if known).

    Value::make_iterable

    fn Value::make_iterable(maker : () -> Iter[Value]) -> Value

    Creates an iterable that iterates over the iterator produced by maker. The maker is invoked every time the value is iterated.

    Value::make_object_map

    fn Value::make_object_map(keys : () -> Iter[Value], get : (Value) -> Value?) -> Value

    Creates a map object from closures: keys enumerates the keys and get looks up a value by key.

    Value::make_one_shot_iterator

    fn Value::make_one_shot_iterator(iter : Iter[Value]) -> Value

    Creates an iterable that can only be iterated over once.

    Value::none

    fn Value::none() -> Value

    The none value.

    Value::reverse

    fn Value::reverse(self : Value) -> Value raise TemplateError

    Returns a reversed view of this value.

    This is implemented for the following types with the following behaviors: undefined or none (returns itself), strings (reverses the characters), bytes, sequences and iterables.

    Value::to_json_string

    fn Value::to_json_string(self : Value, indent? : Int) -> String raise TemplateError

    Serializes the value to JSON. With indent the output is pretty printed.

    Value::to_str

    fn Value::to_str(self : Value) -> String?

    Like as_str but bytes are decoded lossily.

    Value::to_string

    fn Value::to_string(self : Value) -> String

    Formats the value like MiniJinja's Display (what {{ value }} renders).

    Value::try_iter

    fn Value::try_iter(self : Value) -> Iter[Value] raise TemplateError

    Iterates over the value.

    Depending on the kind of the value the iterator has a different behavior: maps yield their keys, sequences and iterables their items, strings their characters and undefined/none values nothing.

    Value::undefined

    fn Value::undefined() -> Value

    The undefined value.

    ValueKind

    pub(all) enum ValueKind {
    Undefined
    Null
    Bool
    Number
    String
    Bytes
    Seq
    Map
    Iterable
    Plain
    Invalid
    } derive(Compare, Eq,
    Debug
    )

    Describes the kind of value.
    impl Show for ValueKind

    ValueKind::to_string

    fn ValueKind::to_string(self : ValueKind) -> String

    WhitespaceConfig

    type WhitespaceConfig

    Internal config struct to control whitespace in the engine.

    builtin_filter

    fn builtin_filter(name : String) -> Value?

    Returns one of the built-in filters by name (independent of any environment). The returned value is callable with Value::call; the first argument is the value the filter is applied to.

    test {
    let env = @minijinja.Environment::empty()
    let state = env.empty_state()
    guard @minijinja.builtin_filter("upper") is Some(upper) else {
    fail("missing")
    }
    inspect(
    upper.call(state, [@minijinja.Value::from_string("hi")]),
    content="HI",
    )
    }

    builtin_function

    fn builtin_function(name : String) -> Value?

    Returns one of the built-in global functions (range, dict, debug, namespace) by name.

    builtin_test

    fn builtin_test(name : String) -> Value?

    Returns one of the built-in tests by name (independent of any environment).

    debug_ast

    fn debug_ast(source : String, name : String) -> String raise TemplateError

    Parses source with the default syntax and returns the pretty Debug representation ({:#?}) of the AST.

    This mirrors upstream's machinery::parse and is meant for debugging tools such as the CLI's --dump=ast.

    debug_tokens

    fn debug_tokens(source : String, trim_blocks? : Bool, lstrip_blocks? : Bool) -> Array[String] raise TemplateError

    Tokenizes source with the default syntax and returns the Debug representation of every token (eg: TemplateData("Hello ")).

    This mirrors upstream's machinery::tokenize and is meant for debugging tools such as the CLI's --dump=tokens.

    default_auto_escape_callback

    fn default_auto_escape_callback(name : String) -> AutoEscape

    The default logic for auto escaping based on file extension.

    • Html: .html, .htm, .xml
    • Json: .json, .json5, .js, .yaml, .yml
    • NoEscape: all others

    Additionally .j2, .jinja2 and .jinja are stripped first.

    format_string

    fn format_string(style : FormatStyle, format_str : String, args : Array[Value]) -> String raise TemplateError

    Formats a string with Python formatting semantics.

    With [FormatStyle::Printf] the % operator semantics are used, with [FormatStyle::StrFormat] the str.format semantics (keyword arguments are passed as a trailing kwargs value).

    html_escape

    fn html_escape(s : String) -> String

    HTML escapes a string (<, >, &, ", ' and /).

    merge_maps

    fn merge_maps(values : Array[Value]) -> Value

    Merges multiple maps (or map-like values) into a single lazy map. Later maps take precedence.