Trait minijinja::filters::Filter

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

A utility trait that represents filters.

This trait is used by the add_filter method to abstract over different types of functions that implement filters. Filters are functions which at the very least accept the State by reference as first parameter and the value that that the filter is applied to as second. Additionally up to 4 further parameters are supported.

A filter can return any of the following types:

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

Filters accept one mandatory parameter which is the value the filter is applied to and up to 4 extra parameters. The extra 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 filters see filters.

§Basic Example

use minijinja::State;

fn slugify(value: String) -> String {
    value.to_lowercase().split_whitespace().collect::<Vec<_>>().join("-")
}

env.add_filter("slugify", slugify);
{{ "Foo Bar Baz"|slugify }} -> foo-bar-baz

§Arguments and 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) }} -> Bar

§Variadic

use minijinja::value::Rest;

fn pyjoin(joiner: String, values: Rest<String>) -> String {
    values.join(&joiner)
}

env.add_filter("pyjoin", pyjoin);
{{ "|".join(1, 2, 3) }} -> 1|2|3

Implementors§

source§

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

source§

impl<Func, Rv, A> Filter<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> Filter<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> Filter<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> Filter<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> Filter<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>,