Custom template tags
Add your own filters and functions to umbral templates from a plugin via Plugin::template_registrars.
Custom template tags
A plugin can extend the template engine with its own filters and tags through the Plugin::template_registrars hook: the plugin returns closures that mutate the minijinja Environment at engine-build time, adding filters, functions, and globals that every app-level template can then use.
The hook
use umbral::prelude::*;use umbral::templates::TemplateRegistrar; struct HumanizePlugin; impl Plugin for HumanizePlugin { fn name(&self) -> &'static str { "humanize" } fn template_registrars(&self) -> Vec<TemplateRegistrar> { vec![Box::new(|env| { // A filter: {{ "hello" | shout }} -> "HELLO" env.add_filter("shout", |s: String| s.to_uppercase()); // A function: {{ pluralize(count, "item", "items") }} env.add_function("pluralize", |n: i64, one: String, many: String| { if n == 1 { one } else { many } }); })] }}<p>{{ heading | shout }}</p><p>{{ cart.count }} {{ pluralize(cart.count, "item", "items") }}</p>Register the plugin on the builder as usual and the tags are live:
App::builder() .plugin(HumanizePlugin) .build()?;Rules
Closures are owned and 'static
Applied after the built-ins
Fn, not FnOnce
What you can add
A registrar has the full minijinja Environment API:
| Call | Adds | Used in a template as |
|---|---|---|
env.add_filter("name", f) | a pipe filter | {{ value \| name(arg) }} |
env.add_function("name", f) | a callable | {{ name(arg) }} |
env.add_global("name", value) | a constant value | {{ name }} |
Filter and function arguments are deserialized from the template call: take String, i64, f64, bool, Option<T> for optional args, or any serde::Deserialize type. Return anything serde::Serialize, or minijinja::Value::from_safe_string(...) to mark generated HTML safe from autoescape (as the markdown filter does).
See also
- Template Filters and Helpers: the built-in filters and globals your tags sit alongside.
- minijinja
EnvironmentAPI: everyadd_*method. crates/umbral-core/src/templates.rs(now/currency) for reference implementations of a built-in function and filter.