Trait rocket_dyn_templates::minijinja::functions::Function

source ·
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.

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

Implementors§

source§

impl<Func, Rv> Function<Rv, ()> for Func
where Func: Fn() -> Rv + Send + Sync + 'static, Rv: FunctionResult,

source§

impl<Func, Rv, A> Function<Rv, (A,)> for Func
where Func: Fn(A) -> Rv + Send + Sync + 'static, Rv: FunctionResult, A: for<'a> ArgType<'a>,

source§

impl<Func, Rv, A, B> Function<Rv, (A, B)> for Func
where Func: Fn(A, B) -> Rv + Send + Sync + 'static, Rv: FunctionResult, A: for<'a> ArgType<'a>, B: for<'a> ArgType<'a>,

source§

impl<Func, Rv, A, B, C> Function<Rv, (A, B, C)> for Func
where Func: Fn(A, B, C) -> Rv + Send + Sync + 'static, Rv: FunctionResult, A: for<'a> ArgType<'a>, B: for<'a> ArgType<'a>, C: for<'a> ArgType<'a>,

source§

impl<Func, Rv, A, B, C, D> Function<Rv, (A, B, C, D)> for Func
where Func: Fn(A, B, C, D) -> Rv + Send + Sync + 'static, Rv: FunctionResult, A: for<'a> ArgType<'a>, B: for<'a> ArgType<'a>, C: for<'a> ArgType<'a>, D: for<'a> ArgType<'a>,

source§

impl<Func, Rv, A, B, C, D, E> Function<Rv, (A, B, C, D, E)> for Func
where Func: Fn(A, B, C, D, E) -> Rv + Send + Sync + 'static, Rv: FunctionResult, A: for<'a> ArgType<'a>, B: for<'a> ArgType<'a>, C: for<'a> ArgType<'a>, D: for<'a> ArgType<'a>, E: for<'a> ArgType<'a>,