-
|
I have some structs that require special formatting. I'd like to use their Is there a way to write a generic filter that takes any struct that can be deserialized and has a display implementation? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
|
Not like this. If you work with objects via use std::fmt;
use std::sync::Arc;
use minijinja::value::{Object, ObjectRepr};
use minijinja::{context, Environment, Value};
#[derive(Debug)]
struct PhoneNumber {
digits: Vec<u8>,
}
impl Object for PhoneNumber {
fn repr(self: &Arc<Self>) -> ObjectRepr {
ObjectRepr::Plain
}
fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "+")?;
for digit in &self.digits {
write!(f, "{}", digit)?;
}
Ok(())
}
}
fn main() {
let mut env = Environment::new();
env.add_template("hello.txt", "Call me at {{ number }}!")
.unwrap();
let template = env.get_template("hello.txt").unwrap();
let number = Value::from_object(PhoneNumber {
digits: vec![2, 3, 5, 2, 1, 5],
});
println!("{}", template.render(context!(number)).unwrap());
}Objects are quite powerful and they are highly dynamic, so you have more flexibility. |
Beta Was this translation helpful? Give feedback.
Not like this. If you work with objects via
ViaDeserializeminijinja will need the type information carried side by side like this. However if your objects likePhoneNumber,Currencyetc. were to implementObjectthen you could pass it asValue::from_object(...)to the context and pass it asValueto the filter: