mirror of
https://github.com/askama-rs/askama.git
synced 2025-10-02 15:25:19 +00:00
axum: add (try_)into_response()
This commit is contained in:
parent
961db59be5
commit
5f2b6133ac
@ -2,20 +2,27 @@
|
||||
#![deny(elided_lifetimes_in_paths)]
|
||||
#![deny(unreachable_pub)]
|
||||
|
||||
#[doc(no_inline)]
|
||||
pub use askama::*;
|
||||
pub use axum_core::response::{IntoResponse, Response};
|
||||
use http::StatusCode;
|
||||
#[doc(no_inline)]
|
||||
pub use axum_core;
|
||||
use axum_core::response::{IntoResponse, Response};
|
||||
|
||||
pub fn into_response<T: Template>(t: &T) -> Response {
|
||||
match t.render() {
|
||||
Ok(body) => {
|
||||
let headers = [(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::HeaderValue::from_static(T::MIME_TYPE),
|
||||
)];
|
||||
|
||||
(headers, body).into_response()
|
||||
}
|
||||
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||
}
|
||||
/// Render a [`Template`] into a [`Response`], or render an error page.
|
||||
pub fn into_response<T: ?Sized + askama::Template>(tmpl: &T) -> Response {
|
||||
try_into_response(tmpl)
|
||||
.map_err(|err| axum_core::response::ErrorResponse::from(err.to_string()))
|
||||
.into_response()
|
||||
}
|
||||
|
||||
/// Try to render a [`Template`] into a [`Response`].
|
||||
pub fn try_into_response<T: ?Sized + askama::Template>(tmpl: &T) -> Result<Response, Error> {
|
||||
let value = tmpl.render()?.into();
|
||||
Response::builder()
|
||||
.header(
|
||||
http::header::CONTENT_TYPE,
|
||||
http::header::HeaderValue::from_static(T::MIME_TYPE),
|
||||
)
|
||||
.body(value)
|
||||
.map_err(|err| Error::Custom(err.into()))
|
||||
}
|
||||
|
@ -165,11 +165,15 @@ impl<'a> Generator<'a> {
|
||||
// Implement Axum's `IntoResponse`.
|
||||
#[cfg(feature = "with-axum")]
|
||||
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(
|
||||
"fn into_response(self)\
|
||||
-> ::askama_axum::Response {",
|
||||
-> ::askama_axum::axum_core::response::Response {",
|
||||
)?;
|
||||
buf.writeln("::askama_axum::into_response(&self)")?;
|
||||
buf.writeln("}")?;
|
||||
|
Loading…
x
Reference in New Issue
Block a user