axum: add (try_)into_response()

This commit is contained in:
René Kijewski 2024-03-06 21:51:21 +01:00 committed by Dirkjan Ochtman
parent 961db59be5
commit 5f2b6133ac
2 changed files with 27 additions and 16 deletions

View File

@ -2,20 +2,27 @@
#![deny(elided_lifetimes_in_paths)] #![deny(elided_lifetimes_in_paths)]
#![deny(unreachable_pub)] #![deny(unreachable_pub)]
#[doc(no_inline)]
pub use askama::*; pub use askama::*;
pub use axum_core::response::{IntoResponse, Response}; #[doc(no_inline)]
use http::StatusCode; pub use axum_core;
use axum_core::response::{IntoResponse, Response};
pub fn into_response<T: Template>(t: &T) -> Response { /// Render a [`Template`] into a [`Response`], or render an error page.
match t.render() { pub fn into_response<T: ?Sized + askama::Template>(tmpl: &T) -> Response {
Ok(body) => { try_into_response(tmpl)
let headers = [( .map_err(|err| axum_core::response::ErrorResponse::from(err.to_string()))
http::header::CONTENT_TYPE, .into_response()
http::HeaderValue::from_static(T::MIME_TYPE), }
)];
/// Try to render a [`Template`] into a [`Response`].
(headers, body).into_response() pub fn try_into_response<T: ?Sized + askama::Template>(tmpl: &T) -> Result<Response, Error> {
} let value = tmpl.render()?.into();
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), Response::builder()
} .header(
http::header::CONTENT_TYPE,
http::header::HeaderValue::from_static(T::MIME_TYPE),
)
.body(value)
.map_err(|err| Error::Custom(err.into()))
} }

View File

@ -165,11 +165,15 @@ impl<'a> Generator<'a> {
// Implement Axum's `IntoResponse`. // Implement Axum's `IntoResponse`.
#[cfg(feature = "with-axum")] #[cfg(feature = "with-axum")]
fn impl_axum_into_response(&mut self, buf: &mut Buffer) -> Result<(), CompileError> { fn impl_axum_into_response(&mut self, buf: &mut Buffer) -> Result<(), CompileError> {
self.write_header(buf, "::askama_axum::IntoResponse", None)?; self.write_header(
buf,
"::askama_axum::axum_core::response::IntoResponse",
None,
)?;
buf.writeln("#[inline]")?; buf.writeln("#[inline]")?;
buf.writeln( buf.writeln(
"fn into_response(self)\ "fn into_response(self)\
-> ::askama_axum::Response {", -> ::askama_axum::axum_core::response::Response {",
)?; )?;
buf.writeln("::askama_axum::into_response(&self)")?; buf.writeln("::askama_axum::into_response(&self)")?;
buf.writeln("}")?; buf.writeln("}")?;