Skip to main content

rocket_dyn_templates/engine/
tera.rs

1use std::path::Path;
2use std::error::Error;
3
4use tera::{Context, Tera};
5use rocket::serde::Serialize;
6
7use crate::engine::Engine;
8
9/// Extensions of template names for which HTML escaping is enabled.
10const MARKUP_EXTENSIONS: &[&str] = &["html", "htm", "xml", "xhtml", "svg"];
11
12/// Returns the suffixes of template names for which HTML escaping is enabled:
13/// every ASCII case variant of each markup extension, on its own (`.HtMl`) and
14/// followed by the engine extension (`.HtMl.tera`).
15///
16/// Tera only matches suffixes exactly, so each variant is listed. The engine
17/// extension is included for templates registered directly with Tera under a
18/// name that ends with it, such as `email.html.tera`.
19fn autoescape_suffixes() -> Vec<String> {
20    let mut suffixes = vec![];
21    for ext in MARKUP_EXTENSIONS {
22        for mask in 0..1u32 << ext.len() {
23            let variant = ext.chars().enumerate()
24                .map(|(i, c)| if mask & (1 << i) != 0 { c.to_ascii_uppercase() } else { c })
25                .collect::<String>();
26
27            suffixes.push(format!(".{variant}.{}", Tera::EXT));
28            suffixes.push(format!(".{variant}"));
29        }
30    }
31
32    suffixes
33}
34
35impl Engine for Tera {
36    const EXT: &'static str = "tera";
37
38    fn init<'a>(_: impl Iterator<Item = (&'a str, &'a Path)>) -> Self {
39        // Create the Tera instance.
40        let mut tera = Tera::default();
41        tera.autoescape_on(autoescape_suffixes());
42        tera
43    }
44
45    fn load<'a>(&mut self, templates: impl Iterator<Item = (&'a str, &'a Path)>) -> Option<()> {
46        // Collect into a tuple of (name, path) for Tera. If we register one at
47        // a time, it will complain about unregistered base templates.
48        let files = templates.map(|(name, path)| (path, Some(name)));
49
50        // Finally try to tell Tera about all of the templates.
51        if let Err(e) = self.add_template_files(files) {
52            span_error!("templating", "Tera templating initialization failed" => {
53                let mut error = Some(&e as &dyn Error);
54                while let Some(err) = error {
55                    error!("{err}");
56                    error = err.source();
57                }
58            });
59
60            None
61        } else {
62            Some(())
63        }
64    }
65
66    fn render<C: Serialize>(&self, template: &str, context: C) -> Option<String> {
67        if !self.contains_template(template) {
68            error!(template, "requested template does not exist");
69            return None;
70        };
71
72        let tera_ctx = Context::from_serialize(&context)
73            .map_err(|e| error!("Tera context error: {}.", e))
74            .ok()?;
75
76        match Tera::render(self, template, &tera_ctx) {
77            Ok(string) => Some(string),
78            Err(e) => {
79                span_error!("templating", template, "failed to render Tera template" => {
80                    let mut error = Some(&e as &dyn Error);
81                    while let Some(err) = error {
82                        error!("{err}");
83                        error = err.source();
84                    }
85                });
86
87                None
88            }
89        }
90    }
91}