trillium_ructe/
lib.rs

1#![forbid(unsafe_code)]
2use trillium::{Conn, KnownHeaderName::ContentType};
3
4/**
5Renders a template and sets content-type as "text/html; charset=utf-8" or returns the conn with a 500 status.
6```ignore
7use trillium::Conn;
8use trillium_ructe::RucteConnExt;
9
10include!(concat!(env!("OUT_DIR"), "/templates.rs"));
11
12fn main() {
13    trillium_smol::run(|conn: Conn| async move {
14        // helloworld.rs.html contents:
15        //  @(text: &str)
16        //  <h1>@text</h1>
17        conn.render_html(|o| templates::helloworld(o, "hello world"))
18    });
19}
20
21```
22*/
23
24pub trait RucteConnExt {
25    /// Render a ructe template to this conn's body.
26    ///
27    /// Allocates a default buffer size of 1kb
28    fn render<F>(self, render_fn: F) -> Self
29    where
30        F: FnOnce(&mut Vec<u8>) -> std::io::Result<()>;
31
32    /// Render a ructe template to this conn's body, starting with an
33    /// allocated buffer of the supplied size in bytes.
34    fn render_with_size_estimate<F>(self, render_fn: F, size_estimate: usize) -> Self
35    where
36        F: FnOnce(&mut Vec<u8>) -> std::io::Result<()>;
37
38    /// Render a ructe template to this conn's body and set a content
39    /// type header of text/html.
40    ///
41    /// Allocates a default buffer size of 1kb.
42    fn render_html<F>(self, render_fn: F) -> Self
43    where
44        F: FnOnce(&mut Vec<u8>) -> std::io::Result<()>;
45}
46
47impl RucteConnExt for Conn {
48    fn render<F>(self, render_fn: F) -> Self
49    where
50        F: FnOnce(&mut Vec<u8>) -> std::io::Result<()>,
51    {
52        self.render_with_size_estimate(render_fn, 1024)
53    }
54
55    fn render_html<F>(self, render_fn: F) -> Self
56    where
57        F: FnOnce(&mut Vec<u8>) -> std::io::Result<()>,
58    {
59        self.render(render_fn)
60            .with_header(ContentType, "text/html; charset=utf-8")
61    }
62
63    fn render_with_size_estimate<F>(self, render_fn: F, size_estimate: usize) -> Self
64    where
65        F: FnOnce(&mut Vec<u8>) -> std::io::Result<()>,
66    {
67        let mut body = Vec::with_capacity(size_estimate);
68        trillium::conn_try!(render_fn(&mut body), self);
69        self.ok(body)
70    }
71}