diff options
-rw-r--r-- | askama/src/lib.rs | 15 | ||||
-rw-r--r-- | testing/tests/actix_web.rs | 20 |
2 files changed, 34 insertions, 1 deletions
diff --git a/askama/src/lib.rs b/askama/src/lib.rs index a0d641b..1d66feb 100644 --- a/askama/src/lib.rs +++ b/askama/src/lib.rs @@ -492,6 +492,21 @@ pub mod actix_web { let ctype = get_mime_type(ext).to_string(); Ok(HttpResponse::Ok().content_type(ctype.as_str()).body(rsp)) } + + pub trait TemplateResponder { + fn responder(&self) -> Result<HttpResponse, Error>; + } + + impl<T: super::Template> TemplateResponder for T { + fn responder(&self) -> Result<HttpResponse, Error> { + let rsp = self + .render() + .map_err(|_| ErrorInternalServerError("Template render error"))?; + let ext = T::extension().unwrap_or(""); + let ctype = get_mime_type(ext).to_string(); + Ok(HttpResponse::Ok().content_type(ctype.as_str()).body(rsp)) + } + } } #[cfg(feature = "with-gotham")] diff --git a/testing/tests/actix_web.rs b/testing/tests/actix_web.rs index d40830f..267736d 100644 --- a/testing/tests/actix_web.rs +++ b/testing/tests/actix_web.rs @@ -2,7 +2,7 @@ use actix_web::http::header::CONTENT_TYPE; use actix_web::test; use actix_web::HttpMessage; -use askama::Template; +use askama::{actix_web::TemplateResponder, Template}; use bytes::Bytes; #[derive(Template)] @@ -23,3 +23,21 @@ fn test_actix_web() { let bytes = srv.execute(response.body()).unwrap(); assert_eq!(bytes, Bytes::from_static("Hello, world!".as_ref())); } + +#[test] +fn test_actix_web_responder() { + let mut srv = test::TestServer::new(|app| { + app.handler(|_| { + let name = "world".to_owned(); + HelloTemplate { name: &name }.responder() + }) + }); + + let request = srv.get().finish().unwrap(); + let response = srv.execute(request.send()).unwrap(); + assert!(response.status().is_success()); + assert_eq!(response.headers().get(CONTENT_TYPE).unwrap(), "text/html"); + + let bytes = srv.execute(response.body()).unwrap(); + assert_eq!(bytes, Bytes::from_static("Hello, world!".as_ref())); +} |