diff options
author | Zizheng Tai <zizheng.tai@gmail.com> | 2019-01-26 22:06:51 -0800 |
---|---|---|
committer | Dirkjan Ochtman <dirkjan@ochtman.nl> | 2019-02-20 16:18:23 +0100 |
commit | bf9e7cc049d7a16cdd3718df82870bf5cc4809b9 (patch) | |
tree | 329ca6bdd89fa2cb81bba4e6be5789a199043727 | |
parent | 9aa40569b4a2dc76474d3e4d220afc12b065b511 (diff) | |
download | askama-bf9e7cc049d7a16cdd3718df82870bf5cc4809b9.tar.gz askama-bf9e7cc049d7a16cdd3718df82870bf5cc4809b9.tar.bz2 askama-bf9e7cc049d7a16cdd3718df82870bf5cc4809b9.zip |
Add TemplateResponder trait for integration with actix-web
Diffstat (limited to '')
-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())); +} |