Created
January 24, 2023 22:30
-
-
Save MadFaill/bed74ae70e0ea425848da32a911acfb2 to your computer and use it in GitHub Desktop.
Askama::Template Rocket response responder implement macro
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[macro_use] | |
use askama_rocket::{Template}; | |
use rocket::futures::executor::block_on; | |
use rocket::http::{ContentType, Status, Header}; | |
use rocket::local::asynchronous::Client; | |
use std::io::Cursor; | |
pub use askama::*; | |
pub use rocket::request::Request; | |
use rocket::response::Response; | |
pub use rocket::response::{Responder, Result}; | |
/// # template_responder | |
/// | |
/// Askama::Template Rocket response responder implement macro | |
/// | |
/// | |
/// # Arguments | |
/// | |
/// * `ident`: Template structure | |
/// | |
/// # Examples | |
/// | |
/// ``` | |
/// template_responder!(Index); // Impl rocket Response Responder for Index | |
/// #[derive(Template)] // Template parser/builder trait | |
/// #[template(path = "index.html")] // template name | |
/// pub struct Index<'a> { | |
/// pub title: &'a str, | |
/// } | |
/// | |
/// ... | |
/// | |
/// #[get("/")] | |
/// pub fn index() -> Index<'static> { | |
/// Index { title: "Index",} | |
/// } | |
/// ``` | |
macro_rules! impl_template_responder { | |
($t:ident) => { | |
impl <'r>Responder<'r, 'r> for $t<'_> { | |
fn respond_to<'o>(self, _: &'r Request<'_>) -> Result<'static> { | |
respond(&self) | |
} | |
} | |
} | |
} | |
impl_template_responder!(Index); | |
#[derive(Template)] | |
#[template(path = "index.html")] | |
pub struct Index<'a> { | |
pub title: &'a str, | |
} | |
// got from there: askama_rocket::respond | |
// unfortunately it's impossible to implement existed one... | |
fn respond<T: Template>(t: &T) -> Result<'static> { | |
let rsp = t.render().map_err(|_| Status::InternalServerError)?; | |
Response::build() | |
.header(Header::new("content-type", T::MIME_TYPE)) | |
.sized_body(rsp.len(), Cursor::new(rsp)) | |
.ok() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment