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
whereRv
implementsInto<Value>
Result<Rv, Error>
whereRv
implementsInto<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