rocket_dyn_templates/engine/
tera.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use std::path::Path;
use std::error::Error;

use tera::{Context, Tera};
use rocket::serde::Serialize;

use crate::engine::Engine;

impl Engine for Tera {
    const EXT: &'static str = "tera";

    fn init<'a>(templates: impl Iterator<Item = (&'a str, &'a Path)>) -> Option<Self> {
        // Create the Tera instance.
        let mut tera = Tera::default();
        let ext = [".html.tera", ".htm.tera", ".xml.tera", ".html", ".htm", ".xml"];
        tera.autoescape_on(ext.to_vec());

        // Collect into a tuple of (name, path) for Tera. If we register one at
        // a time, it will complain about unregistered base templates.
        let files = templates.map(|(name, path)| (path, Some(name)));

        // Finally try to tell Tera about all of the templates.
        if let Err(e) = tera.add_template_files(files) {
            error!("Failed to initialize Tera templating.");

            let mut error = Some(&e as &dyn Error);
            while let Some(err) = error {
                info_!("{}", err);
                error = err.source();
            }

            None
        } else {
            Some(tera)
        }
    }

    fn render<C: Serialize>(&self, name: &str, context: C) -> Option<String> {
        if self.get_template(name).is_err() {
            error_!("Tera template '{}' does not exist.", name);
            return None;
        };

        let tera_ctx = Context::from_serialize(context)
            .map_err(|e| error_!("Tera context error: {}.", e))
            .ok()?;

        match Tera::render(self, name, &tera_ctx) {
            Ok(string) => Some(string),
            Err(e) => {
                error_!("Error rendering Tera template '{name}': {e}");
                let mut error = Some(&e as &dyn Error);
                while let Some(err) = error {
                    error_!("{}", err);
                    error = err.source();
                }

                None
            }
        }
    }
}