rocket_dyn_templates/engine/
handlebars.rs
1use std::path::Path;
2
3use handlebars::Handlebars;
4use rocket::serde::Serialize;
5
6use crate::engine::Engine;
7
8impl Engine for Handlebars<'static> {
9 const EXT: &'static str = "hbs";
10
11 fn init<'a>(templates: impl Iterator<Item = (&'a str, &'a Path)>) -> Option<Self> {
12 let mut hb = Handlebars::new();
13 let mut ok = true;
14 for (template, path) in templates {
15 if let Err(e) = hb.register_template_file(template, path) {
16 error!(template, path = %path.display(),
17 "failed to register Handlebars template: {e}");
18
19 ok = false;
20 }
21 }
22
23 ok.then_some(hb)
24 }
25
26 fn render<C: Serialize>(&self, template: &str, context: C) -> Option<String> {
27 if self.get_template(template).is_none() {
28 error!(template, "requested Handlebars template does not exist.");
29 return None;
30 }
31
32 Handlebars::render(self, template, &context)
33 .map_err(|e| error!("Handlebars render error: {}", e))
34 .ok()
35 }
36}