Filters
Values such as those obtained from variables can be post-processed
using filters.
Filters are applied to values using the pipe symbol (|) and may
have optional extra arguments in parentheses.
Filters can be chained, in which case the output from one filter
is passed to the next.
{{ "HELLO" | lower }}
Askama has a collection of built-in filters, documented below, but can also include custom filters.
Additionally, the json filter is included in the built-in filters, but is disabled by default.
Enable it with Cargo features (see below for more information).
Built-In Filters
Built-in filters that take (optional) arguments can be called with named arguments, too. The order of the named arguments does not matter, but named arguments must come after positional (i.e. unnamed) arguments.
E.g. the filter pluralize takes two optional arguments: singular and plural
which are singular = "" and plural = "s" by default.
If you are fine with the default empty string for the singular, and you only want to set a
specific plural, then you can call the filter like dog{{ count | pluralize(plural = "gies") }}.
assigned_or
{{ variable_or_expression | assigned_or(fallback) }}
If the variable on the left-hand side is in its “default” state, e.g. an empty "" string,
a 0 integer, a None optional, or an Err(_) result, then the fallback value is printed.
Otherwise the value.
{% let greeting = Some("Hello") %}
{{ greeting.as_ref() | assigned_or("Hi") }}
Hello
If the value is an identifier, then it is first tested of the variable name is defined.
See also [|defined_or][#defined_or].
capitalize
enabled by"alloc"
enabled by"default"
{{ text_to_capitalize | capitalize }}
Capitalize a value. The first character will be uppercase, all others lowercase:
{{ "hello" | capitalize }}
Output:
Hello
center
enabled by"alloc"
enabled by"default"
{{ text_to_center | center(length) }}
Centers the value in a field of a given width:
-{{ "a" | center(5) }}-
Output:
- a -
default
{{ variable_or_expression | default(default_value) }}
{{ variable_or_expression | default(default_value, [[boolean =] true]) }}
This filter works like the Jinja filter of the same name.
If the second argument is not a boolean true, then the filter behaves like [|defined_or][#defined_or].
If it is supplied and true, then the filter behaves like [|assigned_or][#assigned_or].
This filter exists for compatibility with Jinja.
Askama provides [|defined_or][#defined_or] and [|assigned_or][#assigned_or] which both
better express the intention and should generally be used instead of this filter.
defined_or
{{ variable | defined_or(fallback) }}
The left-hand side of the filter must be an identifier.
Return a fallback value if the identifier is undefined:
{% let greeting = "Hello" %}
{{ greeting | defined_or("Hi") }}
Since the variable greeting is defined, the output is its value: Hello.
If you remove the variable, then the output is the default value: Hi:
{{ greeting | defined_or("Hi") }}
See also [|assigned_or][#assigned_or].
deref
{{ expression | deref }}
Dereferences the given argument.
{% let s = String::from("a") | ref %}
{% if s | deref == String::from("b") %}
{% endif %}
will become:
let s = &String::from("a");
if *s == String::from("b") {}
escape | e
{{ text_to_escape | e }}
{{ text_to_escape | escape }}
{{ text_to_escape | escape(escaper) }}
Escapes HTML characters in strings:
{{ "Escape <>&" | e }}
Output:
Escape <>&
Optionally, it is possible to specify and override which escaper is used.
Consider a template where the escaper is configured as escape = "none".
However, somewhere escaping using the HTML escaper is desired.
Then it is possible to override and use the HTML escaper like this:
{{ "Don't Escape <>&" | escape }}
{{ "Don't Escape <>&" | e }}
{{ "Escape <>&" | escape("html") }}
{{ "Escape <>&" | e("html") }}
Output:
Don't Escape <>&
Don't Escape <>&
Escape <>&
Escape <>&
filesizeformat
{{ number_of_bytes | filesizeformat }}
Returns adequate string representation (in KB, ..) of number of bytes:
{{ 1024 | filesizeformat }}
Output:
1.02 KB
Control the resulting precision with the optional precision argument:
{{ 1024 | filesizeformat(precision = 3) }}
Output:
1.024 KB
fmt
enabled by"alloc"
enabled by"default"
{{ expression | fmt("format_string") }}
Formats arguments according to the specified format
The second argument to this filter must be a string literal (as in normal
Rust). The two arguments are passed through to format!() by
the Askama code generator, but the order is swapped to support filter
composition.
{{ value | fmt("{:?}") }}
As an example, this allows filters to be composed like the following.
Which is not possible using the format filter.
{{ value | capitalize | fmt("{:?}") }}
format
enabled by"alloc"
enabled by"default"
{{ "format_string" | format([variables ...]) }}
Formats arguments according to the specified format.
The first argument to this filter must be a string literal (as in normal Rust).
All arguments are passed through to format!() by the Askama code generator.
{{ "{:?}" | format(var) }}
indent
{{ text_to_indent | indent(width, [first], [blank]) }}
Indent newlines with width spaces.
{{ "hello\nfoo\nbar" | indent(4) }}
Output:
hello
foo
bar
The first argument can also be a string that will be used to indent lines.
The first line and blank lines are not indented by default.
The filter has two optional [bool] arguments first and blank, that can be set to true
to indent the first and blank lines, resp.:
{{ "hello\n\nbar" | indent("$ ", true, true) }}
Output:
$ hello
$
$ bar
join
{{ iterable | join(separator) }}
Joins iterable into a string separated by provided argument.
array = &["foo", "bar", "bazz"]
{{ array | join(", ") }}
Output:
foo, bar, bazz
linebreaks
{{ text_to_break | linebreaks }}
Replaces line breaks in plain text with appropriate HTML.
A single newline becomes an HTML line break <br> and a new line followed by a blank line becomes a paragraph break <p>.
{{ "hello\nworld\n\nfrom\naskama" | linebreaks }}
Output:
<p>hello<br />world</p><p>from<br />askama</p>
linebreaksbr
{{ text_to_break | linebreaksbr }}
Converts all newlines in a piece of plain text to HTML line breaks.
{{ "hello\nworld\n\nfrom\naskama" | linebreaks }}
Output:
hello<br />world<br /><br />from<br />askama
paragraphbreaks
{{ text_to_break | paragraphbreaks }}
A new line followed by a blank line becomes <p>, but, unlike linebreaks, single new lines are ignored and no <br/> tags are generated.
Consecutive double line breaks will be reduced down to a single paragraph break.
This is useful in contexts where changing single line breaks to line break tags would interfere with other HTML elements, such as lists and nested <div> tags.
{{ "hello\nworld\n\nfrom\n\n\n\naskama" | paragraphbreaks }}
Output:
<p>hello\nworld</p><p>from</p><p>askama</p>
lower | lowercase
enabled by"alloc"
enabled by"default"
{{ text_to_convert | lower }}
{{ text_to_convert | lowercase }}
Converts to lowercase.
{{ "HELLO" | lower }}
Output:
hello
pluralize
{{ integer | pluralize }}
{{ integer | pluralize([singular = ""], [plural = "s"]) }}
Select a singular or plural version of a word, depending on the input value.
If the value of self.count is +1 or -1, then “cat” is returned, otherwise “cats”:
cat{{ count | pluralize }}
You can override the default empty singular suffix, e.g. to spell “doggo” for a single dog:
dog{{ count | pluralize("go") }}
If the word cannot be declined by simply adding a suffix, then you can also override singular and the plural, too:
{{ count | pluralize("mouse", "mice") }}
More complex languages that know multiple plurals might be impossible to implement with this filter, though.
ref
{{ expression | ref }}
Creates a reference to the given argument.
{{ "a" | ref }}
{{ self.x | ref }}
will become:
&"a"
&self.x
reject
This filter filters out values matching the given value/filter.
With this data:
vec![1, 2, 3, 1]
And this template:
{% for elem in data|reject(1) %}{{ elem }},{% endfor %}
Output will be:
2,3,
For more control over the filtering, you can use a callback instead. Declare a function:
fn is_odd(value: &&u32) -> bool {
**value % 2 != 0
}
Then you can pass the path to the is_odd function:
{% for elem in data|reject(crate::is_odd) %}{{ elem }},{% endfor %}
Output will be:
2,
safe
{{ expression | safe }}
Marks a string (or other Display type) as safe. By default all strings are escaped according to the format.
{{ "<p>I'm Safe</p>" | safe }}
Output:
<p>I'm Safe</p>
title | titlecase
enabled by"alloc"
enabled by"default"
{{ text_to_convert | title }}
{{ text_to_convert | titlecase }}
Return a title cased version of the value. Words will start with uppercase letters, all remaining characters are lowercase.
{{ "hello WORLD" | title }}
Output:
Hello World
trim
enabled by"alloc"
enabled by"default"
{{ text_to_trim | trim }}
Strip leading and trailing whitespace.
{{ " hello " | trim }}
Output:
hello
truncate
{{ text_to_truncate | truncate(length) }}
Limit string length, appends ‘…’ if truncated.
{{ "hello" | truncate(2) }}
Output:
he...
unique
Returns an iterator with all duplicates removed.
This filter is only available with the std feature enabled.
With this data:
vec!["a", "b", "a", "c"]
And this template:
{% for elem in data|unique %}{{ elem }},{% endfor %}
Output will be:
a,b,c,
upper | uppercase
enabled by"alloc"
enabled by"default"
{{ text_to_convert | upper }}
{{ text_to_convert | uppercase }}
Converts to uppercase.
{{ "hello" | upper }}
Output:
HELLO
urlencode | urlencode_strict
enabled by"urlencode"
enabled by"default"
{{ text_to_escape | urlencode }}
{{ text_to_escape | urlencode_strict }}
Percent encodes the string. Replaces reserved characters with the % escape character followed by a byte value as two hexadecimal digits.
{{ "hello?world" | urlencode }}
Output:
hello%3Fworld
With |urlencode all characters except ASCII letters, digits, and _.-~/ are escaped.
With |urlencode_strict a forward slash / is escaped, too.
wordcount
{{ text_with_words | wordcount }}
Count the words in that string.
{{ "askama is sort of cool" | wordcount }}
Output:
5
Optional / feature gated filters
The following filters can be enabled by requesting the respective feature in the Cargo.toml dependencies section, e.g.
[dependencies]
askama = { version = "0.12", features = ["serde_json"] }
json | tojson
enabled by "serde_json"
{{ value_to_serialize | json }}
{{ value_to_serialize | json(indent) }}
Enabling the serde_json feature will enable the use of the json filter.
This will output formatted JSON for any value that implements the required
Serialize trait.
The generated string does not contain ampersands &, chevrons < >, or apostrophes '.
To use it in a <script> you can combine it with the safe filter.
In HTML attributes, you can either use it in quotation marks "{{data | json}}" as is,
or in apostrophes with the (optional) safe filter '{{data | json | safe}}'.
In HTML texts the output of e.g. <pre>{{data | json | safe}}</pre> is safe, too.
Good: <li data-extra="{{data | json}}">…</li>
Good: <li data-extra='{{data | json | safe}}'>…</li>
Good: <pre>{{data | json | safe}}</pre>
Good: <script>var data = {{data | json | safe}};</script>
Bad: <li data-extra="{{data | json | safe}}">…</li>
Bad: <script>var data = {{data | json}};</script>
Bad: <script>var data = "{{data | json | safe}}";</script>
Ugly: <script>var data = "{{data | json}}";</script>
Ugly: <script>var data = '{{data | json | safe}}';</script>
By default, a compact representation of the data is generated, i.e. no whitespaces are generated between individual values. To generate a readable representation, you can either pass an integer how many spaces to use as indentation, or you can pass a string that gets used as prefix:
Prefix with four spaces:
<textarea>{{data | tojson(4)}}</textarea>
Prefix with two characters:
<p>{{data | tojson("\u{a0}\u{a0}")}}</p>
Custom Filters
To define your own filters, either have a module named filters in scope of the context of your
#[derive(Template]) struct, and define the filters as functions within this module;
or call the filter with a path, e.g. {{ value | some_module::my_filter }}. Alternatively, you can also place your custom filter functions in a crate called filters added as dependency to your askama project.
The expressions {{ value | my_filter }} and {{ value | filters::my_filter }} behave identically,
unless “my_filter” happens to be a built-in filter.
Note that built-in filters take precedence, so your custom filters will always be shadowed by built-in filters (if they have the same name). To avoid this, call your custom filters with a full path.
Anatomy of a custom filter function
#[askama::filter_fn]
pub fn example_filter1(
// Value that's piped into the filter within the jinja template.
// This can be of any type. `impl Display` is just an example.
value: impl Display,
// This is askama's runtime values environment. Together with
// values, these two arguments are always passed into a custom filter.
env: &dyn askama::Values
) -> askama::Result<String> {
Ok(format!("{value} | example_filter1"))
}
The basic anatomy of a filter function must always look like this:
- The first argument is the value your custom filter function is applied to during a filter invocation. In this template expression:
{{ 1337 | example_filter1 }}, the value1337will be passed in as first argument to your filter function. - The second argument is always of type
values: &dyn askama::Values, storing askama’s runtime values environment. - Custom filter functions’ return type must be
askama::Result<T>, whereTof the last filter invocation of a filter chain mustimpl Display. In this exemplary filter chain:{{ 1337 | multiply | final_filter }}, themultiplyfilter may returnaskama::Result<MyCustomNonDisplayableStruct>, butfinal_filtermust returnaskama::Result<T>withT: Display, otherwise your template will fail to compile.
Additionally to this basic structure, your custom filter function can also have:
An arbitrary amount of required arguments:
#[askama::filter_fn]
pub fn example_filter2<T: ToString>(
value: impl Display, env: &dyn askama::Values,
// Custom arguments that need to be specified when calling your filter
required0: impl Display,
required1: T,
required2: usize
) -> askama::Result<String> { /* ... */ }
An arbitrary amount of optional arguments (must be located after required arguments in your function signature):
#[askama::filter_fn]
pub fn example_filter3(
value: impl Display, // filter input
env: &dyn askama::Values, // askama runtime values environment
required0: impl Display,
// Custom arguments that may optionally be specified when calling your filter
#[optional(None)] optional0: Option<&str>,
#[optional(Some("I am the default value"))] optional1: Option<&str>,
#[optional("I am the default value")] optional2: &str,
) -> askama::Result<String> { /* ... */ }
Calling custom filters
Thanks to the askama::filter_fn macro, invocations to your custom filter functions can also use named arguments - though currently providing diagnostic compile error messages that are a lot less readable compared to builtin filters, when you’re using them wrong in your templates. All of these are valid invocations of the filter functions above:
{{ 1337 | example_filter2("value0", "value1", 2) }}
{{ "1337" | example_filter2(required0 = "req0", required1 = "req1", required2 = 2) }}
{{ 1337 | example_filter3("req0") }}
{{ 1337 | example_filter3("req0", None) }}
{{ "1337" | example_filter3("req0", None, None) }}
{{ "1337" | example_filter3("req0", None, Some("opt1"), "opt2") }}
{{ "1337" | example_filter3("req0", optional2 = "opt2") }}
{{ "1337" | example_filter3(required0 = "req0", optional2 = "opt2") }}
Reference Value Passing Issues
Due to the nature of askama’s generated code, you will often encounter a mix of by-value and various degrees of references to your variables in the jinja template. If you declare your custom filter input value as one concrete type, like &str, you will often be confronted with the problem of having to (de)-reference your input variables: {{ value | filter }}, {{ *value | filter }}, {{ **value | filter }}, …
To avoid this, try to declare your filter’s input argument using trait bounds, which are also implemented for references. For example, instead of:
#[askama::filter_fn]
pub fn example_filter4(value: &str, env: &dyn askama::Values) -> askama::Result<String> {}
instead specify value with a trait bound of Display:
#[askama::filter_fn]
pub fn example_filter4(value: impl Display, env: &dyn askama::Values) -> askama::Result<String> {}
as Display is implemented for &str as well as for &&str, &&&str, ….
This cleans up your invocation sites, as no dereferencing (and no additional compile roundtripping) is required.
Examples
Implementing a filter that replaces all instances of "oo" for "aa".
use askama::Template;
#[derive(Template)]
#[template(source = "{{ s | myfilter }}", ext = "txt")]
struct MyFilterTemplate<'a> {
s: &'a str,
}
// Any filter defined in the module `filters` is accessible in your template.
mod filters {
// This filter does not have extra arguments
#[askama::filter_fn]
pub fn myfilter<T: std::fmt::Display>(
value: T,
_env: &dyn askama::Values,
) -> askama::Result<String> {
let s = s.to_string();
Ok(s.replace("oo", "aa"))
}
}
fn main() {
let t = MyFilterTemplate { s: "foo" };
assert_eq!(t.render().unwrap(), "faa");
}
Implementing a filter that replaces all instances of "oo" for n times "a".
use askama::Template;
#[derive(Template)]
#[template(source = "{{ s | myfilter(4) }}", ext = "txt")]
struct MyFilterTemplate<'a> {
s: &'a str,
}
// Any filter defined in the module `filters` is accessible in your template.
mod filters {
// This filter requires a `usize` input when called in templates
#[askama::filter_fn]
pub fn myfilter<T: std::fmt::Display>(
s: T,
_env: &dyn askama::Values,
n: usize,
) -> askama::Result<String> {
let s = s.to_string();
let mut replace = String::with_capacity(n);
replace.extend((0..n).map(|_| "a"));
Ok(s.replace("oo", &replace))
}
}
fn main() {
let t = MyFilterTemplate { s: "foo" };
assert_eq!(t.render().unwrap(), "faaaa");
}
Runtime values
It is possible to access runtime values in custom filters:
// This example contains a custom filter `|cased`.
// Depending on the runtime value `"case"`, the input is either turned
// into lower case, upper case, or left alone, if the runtime value is undefined.
use std::any::Any;
use askama::{Template, Values};
mod filters {
use super::*;
#[askama::filter_fn]
pub fn cased(value: impl ToString, values: &dyn Values) -> askama::Result<String> {
let value = value.to_string();
let case = askama::get_value(values, "case").ok();
Ok(match case {
Some(Case::Lower) => value.to_lowercase(),
Some(Case::Upper) => value.to_uppercase(),
None => value,
})
}
}
#[derive(Debug, Clone, Copy)]
pub enum Case {
Lower,
Upper,
}
#[test]
fn test_runtime_values_in_custom_filters() {
#[derive(Template)]
#[template(ext = "txt", source = "Hello, {{ user | cased }}!")]
struct MyStruct<'a> {
user: &'a str,
}
// The filter source ("wOrLd") should be written in lower case.
let values: (&str, &dyn Any) = ("case", &Case::Lower);
assert_eq!(
MyStruct { user: "wOrLd" }
.render_with_values(&values)
.unwrap(),
"Hello, world!"
);
// The filter source ("wOrLd") should be written in upper case.
let values: (&str, &dyn Any) = ("case", &Case::Upper);
assert_eq!(
MyStruct { user: "wOrLd" }
.render_with_values(&values)
.unwrap(),
"Hello, WORLD!"
);
// The filter source ("wOrLd") should be written as is.
assert_eq!(
MyStruct { user: "wOrLd" }.render().unwrap(),
"Hello, wOrLd!"
);
}
HTML-safe types
Askama will try to avoid escaping types that generate string representations that do not contain
“HTML-unsafe characters”.
HTML-safe characters are characters that can be used in any context in HTML texts and attributes.
The “unsafe” characters are: <, >, &, " and '.
In order to know which types do not need to be escaped, askama has the marker trait
askama::filters::HtmlSafe, and any type that implements that trait won’t get automatically
escaped in a {{expr}} expression.
By default e.g. all primitive integer types are marked as HTML-safe.
You can also mark your custom type MyStruct as HTML-safe using:
impl askama::filters::HtmlSafe for MyStruct {}
This automatically marks references &MyStruct as HTML-safe, too.
Safe output of custom filters
Say, you have a custom filter | strip that removes all HTML-unsafe characters:
fn strip(s: impl ToString) -> Result<String, askama::Error> {
Ok(s.to_string()
.chars()
.filter(|c| !matches!(c, '<' | '>' | '&' | '"' | '\''))
.collect()
)
}
Then you can also mark the output as safe using askama::filters::Safe:
fn strip(s: impl ToString) -> Result<Safe<String>, askama::Error> {
Ok(Safe(...))
}
There also is askama::filters::MaybeSafe that can be used to mark some output as safe,
if you know that some inputs for our filter will always result in a safe output:
fn as_sign(i: i32) -> Result<MaybeSafe<&'static str>, askama::Error> {
match i.into() {
i if i < 0 => Ok(MaybeSafe::NeedsEscaping("<0")),
i if i > 0 => Ok(MaybeSafe::NeedsEscaping(">0")),
_ => Ok(MaybeSafe::Safe("=0")),
}
}