trillium_askama/lib.rs
1#![forbid(unsafe_code)]
2#![deny(
3 clippy::dbg_macro,
4 missing_copy_implementations,
5 rustdoc::missing_crate_level_docs,
6 missing_debug_implementations,
7 missing_docs,
8 nonstandard_style,
9 unused_qualifications
10)]
11
12/*!
13provides support for using the askama compile-time template library
14with trillium. see
15[https://github.com/djc/askama](https://github.com/djc/askama) for
16more information about using askama.
17
18```
19use trillium::Conn;
20use trillium_askama::{AskamaConnExt, Template};
21
22#[derive(Template)]
23#[template(path = "examples/hello.html")]
24struct HelloTemplate<'a> {
25 name: &'a str,
26}
27
28async fn handler(conn: Conn) -> Conn {
29 conn.render(HelloTemplate { name: "trillium" })
30}
31
32use trillium_testing::prelude::*;
33assert_ok!(
34 get("/").on(&handler),
35 "Hello, trillium!",
36 "content-type" => "text/html"
37);
38```
39*/
40
41pub use askama;
42pub use askama::Template;
43use trillium::KnownHeaderName::ContentType;
44
45/// extends trillium conns with the ability to render askama templates
46pub trait AskamaConnExt {
47 /// renders an askama template, halting the conn and setting a 200
48 /// status code. also sets the mime type based on the template
49 /// extension
50 fn render(self, template: impl Template) -> Self;
51}
52
53impl AskamaConnExt for trillium::Conn {
54 fn render(mut self, template: impl Template) -> Self {
55 use askama::DynTemplate;
56 let text = template.render().unwrap();
57 if let Some(extension) = template.extension() {
58 if let Some(mime) = mime_guess::from_ext(extension).first_raw() {
59 self.response_headers_mut().try_insert(ContentType, mime);
60 }
61 }
62
63 self.ok(text)
64 }
65}