Expand description
Global functions and abstractions.
This module provides the abstractions for functions that can registered as
global functions to the environment via
add_function.
§Using Functions
Functions can be called in any place where an expression is valid. They
are useful to retrieve data. Some functions are special and provided
by the engine (like super) within certain context, others are global.
The following is a motivating example:
<pre>{{ debug() }}</pre>§Custom Functions
A custom global function is just a simple rust function which accepts optional arguments and then returns a result. Global functions are typically used to perform a data loading operation. For instance these functions can be used to expose data to the template that hasn’t been provided by the individual render invocation.
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);§Arguments in Custom Functions
All value arguments in custom functions must implement the ArgType trait.
An optional leading &State or &mut State parameter is handled separately.
Standard types, such as String, i32, bool, f64, etc, already implement this trait.
There are also helper types that will make it easier to extract an arguments with custom types.
The Serde<T> type, for instance, can accept any
type T that implements the Deserialize trait from serde.
use minijinja::value::Serde;
#[derive(Deserialize)]
struct Person {
name: String,
age: i32,
}
fn is_adult(person: Serde<Person>) -> bool {
person.age >= 18
}
env.add_function("is_adult", is_adult);§Note on Keyword Arguments
MiniJinja inherits a lot of the runtime model from Jinja2. That includes support for
keyword arguments. These however are a concept not native to Rust which makes them
somewhat uncomfortable to work with. In MiniJinja keyword arguments are implemented by
converting them into an extra parameter represented by a map. That means if you call
a function as foo(1, 2, three=3, four=4) the function gets three arguments:
[1, 2, {"three": 3, "four": 4}]Regular Value arguments reject the internal keyword-argument value. Functions that
declare keyword arguments should use Kwargs. Variadic functions
that need to forward or manually split all arguments can use
ValueOrKwargs.
§Built-in Functions
When the builtins feature is enabled a range of built-in functions are
automatically added to the environment. These are also all provided in
this module. Note though that these functions are not to be
called from Rust code as their exact interface (arguments and return types)
might change from one MiniJinja version to another.
Traits§
- Function
- A utility trait that represents global functions.