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);
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 unconfortable 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}]
If a function wants to disambiugate between a value passed as keyword argument or not,
the the Value::is_kwargs
can be used which returns true
if a value represents
keyword arguments as oppsed to just a map.
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
A utility trait that represents global functions.