maciejhirsz / ramhorns

Fast Mustache template engine implementation in pure Rust.
https://crates.io/crates/ramhorns
Mozilla Public License 2.0
297 stars 29 forks source link

Compatibility with serde #13

Closed ufoscout closed 4 years ago

ufoscout commented 4 years ago

Is it possible to pass a serde serializable struct to the render method?

For example:

#[derive(Serialize, Deserialize)]
struct MyStruct {
   ...
}
let tpl = Template::new(source).unwrap();
let my_struct = MyStruct{}
let rendered = tpl.render(my_struct)

We need to replace rust_mustace with something actively maintained and this library appears to be a good candidate; anyway, the ability to render whatever serializable instance is fundamental for us.

maciejhirsz commented 4 years ago

Sorry for the late response, this crate isn't super maintained either, though it's getting some love right now.

There isn't really an easy way to do this. The Content trait functions very differently from Serialize, and the only way to make this work is to convert MyStruct to a HashMap or some such, which what rust_mustache is doing. At this point you basically throw away all performance Ramhorns provides.

You can, of course, have #[derive(Content, Serialize, Deserialize)] on your struct, in which case you can happily use serde to serialize/deserialize your data and render it in templates, so as long as you are not using any foreign types you are good.