pub trait Function<Rv, Args>:
Send
+ Sync
+ 'staticwhere
Args: for<'a> FunctionArgs<'a>,{ }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 can optionally accept the State by immutable reference as an
implicit parameter in any position. They can instead take &mut State as
their 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:
RvwhereRvimplementsInto<Value>Result<Rv, Error>whereRvimplementsInto<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.
This trait is also used for filters and
tests.
§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") }}§Mutable State
A function which needs to modify the execution state can take &mut State
as its first parameter. Unlike &State, mutable state must be the first
parameter and can only be requested once.
use minijinja::{State, Value};
fn counter(state: &mut State) -> i64 {
let value = state
.get_temp("counter")
.and_then(|value| i64::try_from(value).ok())
.unwrap_or_default()
+ 1;
state.set_temp("counter", Value::from(value));
value
}
env.add_function("counter", counter);§Variadic
use minijinja::value::Rest;
fn sum(values: Rest<i64>) -> i64 {
values.iter().sum()
}
env.add_function("sum", sum);{{ sum(1, 2, 3) }} -> 6§Optional Arguments
fn substr(value: String, start: u32, end: Option<u32>) -> String {
let end = end.unwrap_or(value.len() as _);
value.get(start as usize..end as usize).unwrap_or_default().into()
}
env.add_filter("substr", substr);{{ "Foo Bar Baz"|substr(4) }} -> Bar Baz
{{ "Foo Bar Baz"|substr(4, 7) }} -> BarDyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".