aboutsummaryrefslogtreecommitdiffstats
path: root/askama_actix/src/lib.rs
blob: 7372034eed9a2390d54efba7c354fce7998a69fe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
pub use askama::*;
use bytes::BytesMut;

use actix_web::{error::ErrorInternalServerError, Error, HttpResponse};

pub trait TemplateIntoResponse {
    fn into_response(&self) -> ::std::result::Result<HttpResponse, Error>;
}

impl<T: askama::Template> TemplateIntoResponse for T {
    fn into_response(&self) -> ::std::result::Result<HttpResponse, Error> {
        let mut buffer = BytesMut::with_capacity(self.size_hint());
        self.render_into(&mut buffer)
            .map_err(|_| ErrorInternalServerError("Template parsing error"))?;

        let ctype =
            askama::mime::extension_to_mime_type(self.extension().unwrap_or("txt")).to_string();
        Ok(HttpResponse::Ok()
            .content_type(ctype.as_str())
            .body(buffer.freeze()))
    }
}