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
&State
and value argument, then register 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 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(_state: &State, value: String) -> Result<String, Error> {
Ok(value.to_lowercase().split_whitespace().collect::<Vec<_>>().join("-"))
}
env.add_filter("slugify", slugify);
MiniJinja will perform the necessary conversions automatically via the
FunctionArgs
and Into
traits.
Traits
A utility trait that represents filters.
Functions
builtins
Returns the absolute value of a number.
Batch items.
builtins
Checks if a string starts with another string.
builtins
Dict sorting functionality.
HTML escapes a string.
builtins
Returns the first item from a list.
builtins
Returns a list of pairs (items) from a mapping.
builtins
Joins a sequence by a character
builtins
Returns the last item from a list.
builtins
Returns the “length” of the value
builtins
Converts the input value into a list.
builtins
Converts a value to lowercase.
builtins
Does a string replace.
builtins
Reverses a list or string
builtins
Round the number to a given precision.
Marks a value as safe. This converts it into a string.
Slice an iterable and return a list of lists containing those items.
builtins
Converts a value to title case.
builtins
and json
Dumps a value to JSON.
builtins
Trims a value
builtins
Converts a value to uppercase.
builtins
and urlencode
URL encodes a value.