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
63
64
//! Compiled template. Probably best to use this in release mode so
//! you're not reloading templates on each page view.

use {
    crate::{compile, Result, Stmt},
    std::{fs::File, io::Read, path::Path},
};

/// Compiled HTML template.
pub struct Template {
    source: String,
    compiled: Option<Vec<Stmt>>,
}

impl Template {
    pub fn new(source: String) -> Template {
        Template {
            source,
            compiled: None,
        }
    }

    pub fn stmts(&mut self) -> Result<&[Stmt]> {
        self.compile()?;
        if let Some(stmts) = &self.compiled {
            Ok(stmts)
        } else {
            Ok(&[])
        }
    }

    pub fn compile(&mut self) -> Result<()> {
        if self.compiled.is_none() {
            self.compiled = Some(compile(&self.source)?);
        }
        Ok(())
    }
}

impl From<String> for Template {
    fn from(s: String) -> Template {
        Template::new(s)
    }
}

impl From<&str> for Template {
    fn from(s: &str) -> Template {
        Template::new(s.to_string())
    }
}

impl From<&Path> for Template {
    fn from(p: &Path) -> Template {
        File::open(p).unwrap().into()
    }
}

impl From<File> for Template {
    fn from(mut f: File) -> Template {
        let mut s = String::new();
        f.read_to_string(&mut s).unwrap();
        Template::new(s)
    }
}