Skip to main content

Module filters

Module filters 

Source
Expand description

askama filters for Ocre’s helpers (feature html): {{ post.price|number_to_currency("$") }}.

askama looks custom filters up in a module named filters in scope where the template struct is defined. Bring these in with use ocre::filters; in the controller module (generated controllers do). To add filters of your own, make that module yours and re-export Ocre’s:

mod filters {
    pub use ocre::filters::*;

    /// `{{ name|shout }}`: `Ocre!`.
    #[askama::filter_fn]
    pub fn shout(value: impl std::fmt::Display, _: &dyn askama::Values) -> askama::Result<String> {
        Ok(format!("{value}!"))
    }
}

#[derive(askama::Template)]
#[template(source = "{{ name|shout }} {{ views|number_with_delimiter }}", ext = "html")]
struct Hello {
    name: &'static str,
    views: i64,
}

assert_eq!(askama::Template::render(&Hello { name: "Ocre", views: 12345 }).unwrap(), "Ocre! 12,345");
FilterOutputHelper
{{ views|number_with_delimiter }}1,234,567number_with_delimiter
{{ ratio|number_with_precision(2) }}3.14number_with_precision
{{ price|number_to_currency("$") }}$1,234.50number_to_currency
{{ rate|number_to_percentage(1) }}12.3%number_to_percentage
{{ size|number_to_human_size }}1.5 KBnumber_to_human_size
{{ visits|number_to_human }}1.23 Millionnumber_to_human
{{ post.created_at|time_ago_in_words }} agoabout 3 hours agotime_ago_in_words
{{ from|distance_of_time_in_words(to) }}2 daysdistance_of_time_in_words
{{ post.created_at|strftime("%b %-d, %Y") }}Sep 29, 2026strftime
{{ post.body|excerpt(q, 40) }}...around the match...excerpt
{{ post.body|highlight(q) }}escaped text with <mark>highlight
{{ post.body|word_wrap(72) }}lines of at most 72 charactersword_wrap
{{ post.body|rich_text }}the HTML of a rich_text field, sanitizedsanitize
{{ post.body|plain_text|truncate(80) }}its text, without tagsstrip_tags

askama’s built-in filters cover the rest of Rails’ text helpers: truncate(n), wordcount, linebreaks / linebreaksbr / paragraphbreaks (simple_format), pluralize ({{ n }} post{{ n|pluralize }}), filesizeformat, urlencode, upper / lower / title / capitalize, json and fmt ({{ ratio|fmt("{:.2}") }}).

The items below are generated by [askama::filter_fn]; call the helpers functions from Rust code.

Structs§

distance_of_time_in_words
excerpt
highlight
number_to_currency
number_to_human
number_to_human_size
number_to_percentage
number_with_delimiter
number_with_precision
plain_text
rich_text
strftime
time_ago_in_words
word_wrap