Expand description
Types for value formatters.
Value formatters allow you to change the way a Value
is formatted in the
rendered template. They can be configured on the engine using
set_default_formatter
or
add_formatter
.
This module defines a Formatter
type that is similar to
std::fmt::Formatter
so it should be a familiar API. A mutable reference
to this struct is passed to formatter functions and writing to it will
update the underlying buffer, be it a String
or an arbitrary
std::io::Write
buffer.
All formatter functions must have the following signature.
use upon::{Value, fmt};
Fn(&mut fmt::Formatter<'_>, &Value) -> fmt::Result;
Since Error
implements From<String>
and From<&str>
it is possible
to return custom messages from formatter functions. You can also easily
propagate the standard library std::fmt::Error
.
§Examples
§Escape ASCII
Consider a use case where you want to escape all non-ascii characters in
strings. We could define a value formatter for that using the standard
library function escape_ascii
.
use std::fmt::Write;
use upon::{fmt, Engine, Value};
fn escape_ascii(f: &mut fmt::Formatter<'_>, value: &Value) -> fmt::Result {
match value {
Value::String(s) => write!(f, "{}", s.as_bytes().escape_ascii())?,
v => fmt::default(f, v)?, // fallback to default formatter
};
Ok(())
}
let mut engine = Engine::new();
engine.add_formatter("escape_ascii", escape_ascii);
We could then use this this formatter in templates like this.
{{ user.name | escape_ascii }}
§Error on Value::None
The default
value formatter formats Value::None
as an empty string.
This example demonstrates how you can configure a default formatter to error
instead.
use std::fmt::Write;
use upon::{fmt, Engine, Value};
fn error_on_none(f: &mut fmt::Formatter<'_>, value: &Value) -> fmt::Result {
match value {
Value::None => Err(fmt::Error::from("unable to format None")),
v => fmt::default(f, v), // fallback to default formatter
}
}
let mut engine = Engine::new();
engine.set_default_formatter(&error_on_none);
Structs§
- The error type returned from a formatter function.
- A
std::fmt::Write
façade.
Functions§
- The default value formatter.
Type Aliases§
- The result type returned from a formatter function.