Expand description
Filter functions and abstractions.
MiniJinja inherits from Jinja2 the concept of filter functions. These are functions
which are applied to values to modify them. For example the expression {{ 42|filter(23) }}
invokes the filter filter
with the arguments 42
and 23
.
MiniJinja comes with some built-in filters that are listed below. To create a
custom filter write a function that takes at least a value, then registers it
with add_filter
.
§Using Filters
Using filters in templates is possible in all places an expression is permitted. This means they are not just used for printing but also are useful for iteration or similar situations.
Motivating example:
<dl>
{% for key, value in config|items %}
<dt>{{ key }}
<dd><pre>{{ value|tojson }}</pre>
{% endfor %}
</dl>
§Custom Filters
A custom filter is just a simple function which accepts its inputs as parameters and then returns a new value. For instance the following shows a filter which takes an input value and replaces whitespace with dashes and converts it to lowercase:
fn slugify(value: String) -> String {
value.to_lowercase().split_whitespace().collect::<Vec<_>>().join("-")
}
env.add_filter("slugify", slugify);
MiniJinja will perform the necessary conversions automatically. For more
information see the Filter
trait.
§Accessing State
In some cases it can be necessary to access the execution State
. Since a borrowed
state implements ArgType
it’s possible to add a parameter that holds the state.
For instance the following filter appends the current template name to the string:
use minijinja::{Value, State};
fn append_template(state: &State, value: &Value) -> String {
format!("{}-{}", value, state.name())
}
env.add_filter("append_template", append_template);
§Filter configuration
The recommended pattern for filters to change their behavior is to leverage global variables in the template. For instance take a filter that performs date formatting. You might want to change the default time format format on a per-template basis without having to update every filter invocation. In this case the recommended pattern is to reserve upper case variables and look them up in the filter:
use minijinja::State;
fn timeformat(state: &State, ts: f64) -> String {
let configured_format = state.lookup("TIME_FORMAT");
let format = configured_format
.as_ref()
.and_then(|x| x.as_str())
.unwrap_or("HH:MM:SS");
format_unix_timestamp(ts, format)
}
env.add_filter("timeformat", timeformat);
This then later lets a user override the default either by using
add_global
or by passing it with the
context!
macro or similar.
let ctx = context! {
TIME_FORMAT => "HH:MM",
..other_variables
};
§Built-in Filters
When the builtins
feature is enabled a range of built-in filters 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.
Some additional filters are available in the
minijinja-contrib
crate.
Traits§
- Filter
- A utility trait that represents filters.
Functions§
- abs
builtins
- Returns the absolute value of a number.
- attr
builtins
- Looks up an attribute.
- batch
builtins
- Batch items.
- bool
builtins
- Converts the value into a boolean value.
- capitalize
builtins
- Convert the string with all its characters lowercased apart from the first char which is uppercased.
- default
builtins
- If the value is undefined it will return the passed default value, otherwise the value of the variable:
- dictsort
builtins
- Dict sorting functionality.
- escape
- Escapes a string. By default to HTML.
- first
builtins
- Returns the first item from a list.
- float
builtins
- Converts a value into a float.
- indent
builtins
- indents Value with spaces
- int
builtins
- Converts a value into an integer.
- items
builtins
- Returns a list of pairs (items) from a mapping.
- join
builtins
- Joins a sequence by a character
- last
builtins
- Returns the last item from an iterable or string.
- length
builtins
- Returns the “length” of the value
- list
builtins
- Converts the input value into a list.
- lower
builtins
- Converts a value to lowercase.
- map
builtins
- Applies a filter to a sequence of objects or looks up an attribute.
- max
builtins
- Returns the largest item from the list.
- min
builtins
- Returns the smallest item from the list.
- pprint
builtins
- Pretty print a variable.
- reject
builtins
- Creates a new sequence of values that don’t pass a test.
- rejectattr
builtins
- Creates a new sequence of values of which an attribute does not pass a test.
- replace
builtins
- Does a string replace.
- reverse
builtins
- Reverses an iterable or string
- round
builtins
- Round the number to a given precision.
- safe
- Marks a value as safe. This converts it into a string.
- select
builtins
- Creates a new sequence of values that pass a test.
- selectattr
builtins
- Creates a new sequence of values of which an attribute passes a test.
- slice
builtins
- Slice an iterable and return a list of lists containing those items.
- sort
builtins
- Returns the sorted version of the given list.
- title
builtins
- Converts a value to title case.
- tojson
builtins
andjson
- Dumps a value to JSON.
- trim
builtins
- Trims a value
- unique
builtins
- Returns a list of unique items from the given iterable.
- upper
builtins
- Converts a value to uppercase.
- urlencode
builtins
andurlencode
- URL encodes a value.