From 23ff7ad636b4c0e26d3242747d50b7123831a1a8 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Wed, 20 Feb 2019 20:02:56 +0100 Subject: Simplify actix-web implementations --- askama/src/lib.rs | 21 ++++++--------------- askama_derive/src/generator.rs | 7 ++----- testing/tests/actix_web.rs | 4 ++-- 3 files changed, 10 insertions(+), 22 deletions(-) diff --git a/askama/src/lib.rs b/askama/src/lib.rs index faf2f24..dea5833 100644 --- a/askama/src/lib.rs +++ b/askama/src/lib.rs @@ -500,25 +500,16 @@ pub mod actix_web { }; use self::mime_guess::get_mime_type; - pub fn respond(t: &T, ext: &str) -> Result { - let rsp = t - .render() - .map_err(|_| ErrorInternalServerError("Template parsing error"))?; - let ctype = get_mime_type(ext).to_string(); - Ok(HttpResponse::Ok().content_type(ctype.as_str()).body(rsp)) + pub trait TemplateIntoResponse { + fn into_response(&self) -> Result; } - pub trait TemplateResponder { - fn responder(&self) -> Result; - } - - impl TemplateResponder for T { - fn responder(&self) -> Result { + impl TemplateIntoResponse for T { + fn into_response(&self) -> Result { let rsp = self .render() - .map_err(|_| ErrorInternalServerError("Template render error"))?; - let ext = T::extension().unwrap_or("txt"); - let ctype = get_mime_type(ext).to_string(); + .map_err(|_| ErrorInternalServerError("Template parsing error"))?; + let ctype = get_mime_type(T::extension().unwrap_or("txt")).to_string(); Ok(HttpResponse::Ok().content_type(ctype.as_str()).body(rsp)) } } diff --git a/askama_derive/src/generator.rs b/askama_derive/src/generator.rs index 8f2866e..4a6eb89 100644 --- a/askama_derive/src/generator.rs +++ b/askama_derive/src/generator.rs @@ -234,11 +234,8 @@ impl<'a> Generator<'a> { -> ::std::result::Result {", ); - let ext = match self.input.path.extension() { - Some(s) => s.to_str().unwrap(), - None => "txt", - }; - buf.writeln(&format!("::askama::actix_web::respond(&self, {:?})", ext)); + buf.writeln("use ::askama::actix_web::TemplateIntoResponse;"); + buf.writeln("self.into_response()"); buf.writeln("}"); buf.writeln("}"); diff --git a/testing/tests/actix_web.rs b/testing/tests/actix_web.rs index 267736d..7f2d835 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::{actix_web::TemplateResponder, Template}; +use askama::{actix_web::TemplateIntoResponse, Template}; use bytes::Bytes; #[derive(Template)] @@ -29,7 +29,7 @@ fn test_actix_web_responder() { let mut srv = test::TestServer::new(|app| { app.handler(|_| { let name = "world".to_owned(); - HelloTemplate { name: &name }.responder() + HelloTemplate { name: &name }.into_response() }) }); -- cgit