pub trait Function<Rv, Args>: Send + Sync + 'static { }
Expand description

A utility trait that represents global functions.

This trait is used by the add_function method to abstract over different types of functions.

Functions which at the very least accept the State by reference as first parameter and additionally up to 4 further parameters. They share much of their interface with filters.

A function can return any of the following types:

  • Rv where Rv implements Into<Value>
  • Result<Rv, Error> where Rv implements Into<Value>

The parameters can be marked optional by using Option<T>. The last argument can also use Rest<T> to capture the remaining arguments. All types are supported for which ArgType is implemented.

For a list of built-in functions see functions.

Basic Example

use minijinja::{Error, ErrorKind};

fn include_file(name: String) -> Result<String, Error> {
    std::fs::read_to_string(&name)
        .map_err(|e| Error::new(
            ErrorKind::InvalidOperation,
            "cannot load file"
        ).with_source(e))
}

env.add_function("include_file", include_file);
{{ include_file("filname.txt") }}

Variadic

use minijinja::value::Rest;

fn sum(values: Rest<i64>) -> i64 {
    values.iter().sum()
}

env.add_function("sum", sum);
{{ sum(1, 2, 3) }} -> 6

Implementors