From 48a517335bdaa6d8e72eb0d0fe6512033b83d43e Mon Sep 17 00:00:00 2001 From: Harald Eilertsen Date: Fri, 17 Nov 2017 11:30:32 +0100 Subject: Implement responder for IndexTemplate. This means the actual handler just returns the template, which is then rendered by the responder for that type. Looking into making this generic so the responder can return data in other formats as well, like json or xml. --- src/main.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/main.rs b/src/main.rs index e0501d0..03c34df 100644 --- a/src/main.rs +++ b/src/main.rs @@ -8,7 +8,10 @@ extern crate rocket_blog; use self::diesel::prelude::*; use self::rocket_blog::{schema, models}; -use rocket::response; +use rocket::response::{Response, Responder}; +use rocket::request::Request; +use rocket::http::{ContentType, Status}; +use std::io::Cursor; #[derive(BartDisplay)] #[template = "templates/index.html"] @@ -17,15 +20,24 @@ struct IndexTemplate<'a> { posts: Vec } +impl<'a> Responder<'a> for IndexTemplate<'a> { + fn respond_to(self, _: &Request) -> Result, Status> { + Response::build() + .header(ContentType::HTML) + .sized_body(Cursor::new(format!("{}", &self))) + .ok() + } +} + #[get("/")] -fn index(conn: rocket_blog::DbConn) -> content::Html { +fn index<'a>(conn: rocket_blog::DbConn) -> IndexTemplate<'a> { use schema::posts::dsl::*; let results = posts.filter(published.eq(false)) .limit(5) .load::(&*conn) .expect("Error loading posts"); - content::Html(format!("{}", &IndexTemplate{ title: "Bloggen", posts: results })) + IndexTemplate { title: "Bloggen", posts: results } } fn main() { -- cgit v1.2.3