Skip to main content

chipa_webhooks/
template.rs

1use handlebars::Handlebars;
2use serde_json::Value;
3
4use crate::error::WebhookError;
5
6pub struct TemplateEngine {
7    hbs: Handlebars<'static>,
8}
9
10impl TemplateEngine {
11    pub fn new() -> Self {
12        let mut hbs = Handlebars::new();
13        hbs.set_strict_mode(false);
14        Self { hbs }
15    }
16
17    pub fn register(
18        &mut self,
19        name: &str,
20        template: &str,
21    ) -> Result<(), handlebars::TemplateError> {
22        self.hbs.register_template_string(name, template)
23    }
24
25    pub fn render(&self, name: &str, data: &Value) -> Result<String, WebhookError> {
26        if !self.hbs.has_template(name) {
27            return Err(WebhookError::TemplateNotFound(name.to_owned()));
28        }
29        self.hbs.render(name, data).map_err(WebhookError::from)
30    }
31
32    pub fn has_template(&self, name: &str) -> bool {
33        self.hbs.has_template(name)
34    }
35}
36
37impl Default for TemplateEngine {
38    fn default() -> Self {
39        Self::new()
40    }
41}