logo
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.

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

absbuiltins

Returns the absolute value of a number.

Batch items.

defaultbuiltins

Checks if a string starts with another string.

dictsortbuiltins

Dict sorting functionality.

HTML escapes a string.

firstbuiltins

Returns the first item from a list.

itemsbuiltins

Returns a list of pairs (items) from a mapping.

joinbuiltins

Joins a sequence by a character

lastbuiltins

Returns the last item from a list.

lengthbuiltins

Returns the “length” of the value

listbuiltins

Converts the input value into a list.

lowerbuiltins

Converts a value to lowercase.

replacebuiltins

Does a string replace.

reversebuiltins

Reverses a list or string

roundbuiltins

Round the number to a given precision.

Marks a value as safe. This converts it into a string.

“”“Slice an iterator and return a list of lists containing those items. Useful if you want to create a div containing three ul tags that represent columns:

titlebuiltins

Converts a value to title case.

tojsonbuiltins and json

Dumps a value to JSON.

trimbuiltins

Trims a value

upperbuiltins

Converts a value to uppercase.

urlencodebuiltins and urlencode

URL encodes a value.