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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
use std::{path::PathBuf, sync::Arc};
use tera::{Context, Tera};
use trillium::{async_trait, Conn, Handler};

/**

*/
#[derive(Clone, Debug)]
pub struct TeraHandler(Arc<Tera>);

impl From<PathBuf> for TeraHandler {
    fn from(dir: PathBuf) -> Self {
        dir.to_str().unwrap().into()
    }
}

impl From<&str> for TeraHandler {
    fn from(dir: &str) -> Self {
        Tera::new(dir).unwrap().into()
    }
}

impl From<&String> for TeraHandler {
    fn from(dir: &String) -> Self {
        (**dir).into()
    }
}

impl From<String> for TeraHandler {
    fn from(dir: String) -> Self {
        dir.into()
    }
}

impl From<Tera> for TeraHandler {
    fn from(tera: Tera) -> Self {
        Self(Arc::new(tera))
    }
}

impl From<&[&str]> for TeraHandler {
    fn from(dir_parts: &[&str]) -> Self {
        dir_parts.iter().collect::<PathBuf>().into()
    }
}

impl TeraHandler {
    /// Construct a new TeraHandler from either a `&str` or PathBuf that represents
    /// a directory glob containing templates, or from a
    /// [`tera::Tera`] instance
    /// ```
    /// # fn main() -> tera::Result<()> {
    /// use std::path::PathBuf;
    /// use trillium_tera::TeraHandler;
    /// use std::iter::FromIterator;
    ///
    /// let handler = TeraHandler::new(PathBuf::from_iter([".", "examples", "**", "*.html"]));
    ///
    /// // or
    ///
    /// let handler = TeraHandler::new("examples/*.html");
    ///
    /// // or
    ///
    /// let mut tera = trillium_tera::Tera::default();
    /// tera.add_raw_template("hello.html", "hello {{name}}")?;
    /// let handler = TeraHandler::new(tera);
    /// # Ok(()) }
    /// ```
    pub fn new(tera: impl Into<Self>) -> Self {
        tera.into()
    }

    pub(crate) fn tera(&self) -> &Tera {
        &self.0
    }
}

#[async_trait]
impl Handler for TeraHandler {
    async fn run(&self, conn: Conn) -> Conn {
        conn.with_state(self.clone()).with_state(Context::new())
    }
}