trillium_tera/
tera_handler.rs

1use std::{path::PathBuf, sync::Arc};
2use tera::{Context, Tera};
3use trillium::{async_trait, Conn, Handler};
4
5/**
6
7*/
8#[derive(Clone, Debug)]
9pub struct TeraHandler(Arc<Tera>);
10
11impl From<PathBuf> for TeraHandler {
12    fn from(dir: PathBuf) -> Self {
13        dir.to_str().unwrap().into()
14    }
15}
16
17impl From<&str> for TeraHandler {
18    fn from(dir: &str) -> Self {
19        Tera::new(dir).unwrap().into()
20    }
21}
22
23impl From<&String> for TeraHandler {
24    fn from(dir: &String) -> Self {
25        (**dir).into()
26    }
27}
28
29impl From<String> for TeraHandler {
30    fn from(dir: String) -> Self {
31        dir.into()
32    }
33}
34
35impl From<Tera> for TeraHandler {
36    fn from(tera: Tera) -> Self {
37        Self(Arc::new(tera))
38    }
39}
40
41impl From<&[&str]> for TeraHandler {
42    fn from(dir_parts: &[&str]) -> Self {
43        dir_parts.iter().collect::<PathBuf>().into()
44    }
45}
46
47impl TeraHandler {
48    /// Construct a new TeraHandler from either a `&str` or PathBuf that represents
49    /// a directory glob containing templates, or from a
50    /// [`tera::Tera`] instance
51    /// ```
52    /// # fn main() -> tera::Result<()> {
53    /// use std::path::PathBuf;
54    /// use trillium_tera::TeraHandler;
55    /// use std::iter::FromIterator;
56    ///
57    /// let handler = TeraHandler::new(PathBuf::from_iter([".", "examples", "**", "*.html"]));
58    ///
59    /// // or
60    ///
61    /// let handler = TeraHandler::new("examples/*.html");
62    ///
63    /// // or
64    ///
65    /// let mut tera = trillium_tera::Tera::default();
66    /// tera.add_raw_template("hello.html", "hello {{name}}")?;
67    /// let handler = TeraHandler::new(tera);
68    /// # Ok(()) }
69    /// ```
70    pub fn new(tera: impl Into<Self>) -> Self {
71        tera.into()
72    }
73
74    pub(crate) fn tera(&self) -> &Tera {
75        &self.0
76    }
77}
78
79#[async_trait]
80impl Handler for TeraHandler {
81    async fn run(&self, conn: Conn) -> Conn {
82        conn.with_state(self.clone()).with_state(Context::new())
83    }
84}