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
whereRv
implementsInto<Value>
Result<Rv, Error>
whereRv
implementsInto<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
.
Note: this trait cannot be implemented and only exists drive the
functionality of add_function
and from_function
. If you want
to implement a custom callable, you can directly implement
Object::call
which is what the engine actually uses internally.
§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("filename.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