logo
Expand description

Test functions and abstractions.

Test functions in MiniJinja are like (filters)crate::filters but a different syntax is used to invoke them and they have to return boolean values. For instance the expression {% if foo is odd %} invokes the is_odd test to check if the value is indeed an odd number.

MiniJinja comes with some built-in test functions that are listed below. To create a custom test write a function that takes at least a &State and value argument and returns a boolean result, then register it with add_filter.

Using Tests

Tests are useful to “test” a value in a specific way. For instance if you want to assign different classes to alternating rows one way is using the odd test:

{% if seq is defined %}
  <ul>
  {% for item in seq %}
    <li class="{{ 'even' if loop.index is even else 'odd' }}">{{ item }}</li>
  {% endfor %}
  </ul>
{% endif %}

Custom Tests

A custom test function is just a simple function which accepts inputs as parameters and then returns a bool wrapped in a result. For instance the following shows a test function which takes an input value and checks if it’s lowercase:

fn is_lowercase(_state: &State, value: String) -> Result<bool, Error> {
   Ok(value.chars().all(|x| x.is_lowercase()))
}

env.add_test("lowercase", is_lowercase);

MiniJinja will perform the necessary conversions automatically via the FunctionArgs trait.

Traits

A utility trait that represents filters.

Functions

is_definedbuiltins

Checks if a value is defined.

Checks if the value is ending with a string.

is_evenbuiltins

Checks if a value is even.

is_mappingbuiltins

Checks if this value is a mapping

is_numberbuiltins

Checks if this value is a number.

is_oddbuiltins

Checks if a value is odd.

is_sequencebuiltins

Checks if this value is a sequence

Checks if the value is starting with a string.

is_stringbuiltins

Checks if this value is a string.

is_undefinedbuiltins

Checks if a value is undefined.