Skip to main content

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>(_: impl Iterator<Item = (&'a str, &'a Path)>) -> Self {
12        Handlebars::new()
13    }
14
15    fn load<'a>(&mut self, templates: impl Iterator<Item = (&'a str, &'a Path)>) -> Option<()> {
16        let mut ok = true;
17        for (template, path) in templates {
18            if let Err(e) = self.register_template_file(template, path) {
19                error!(template, path = %path.display(),
20                    "failed to register Handlebars template: {e}");
21
22                ok = false;
23            }
24        }
25
26        ok.then_some(())
27    }
28
29    fn render<C: Serialize>(&self, template: &str, context: C) -> Option<String> {
30        if self.get_template(template).is_none() {
31            error!(template, "requested Handlebars template does not exist.");
32            return None;
33        }
34
35        Handlebars::render(self, template, &context)
36            .map_err(|e| error!("Handlebars render error: {}", e))
37            .ok()
38    }
39}