add method and route to display posts

pull/1/head
kirbylife 2019-11-17 16:09:36 -06:00
parent ad4cd6b028
commit 1832a5bdd5
1 changed files with 28 additions and 1 deletions

View File

@ -74,10 +74,37 @@ fn index(page: Option<i8>) -> Template {
Template::render("index", context)
}
fn get_post(id_number: i32) -> Post {
use schema::posts::dsl::*;
let connection = establish_connection();
let post = posts.find(id_number).first(&connection);
post.unwrap()
}
#[get("/posts/<title>")]
fn show_post(title: String) -> Template {
let mut context = Context::new();
let title_splited: Vec<&str> = title.split('-').collect();
let id = title_splited.last().unwrap().parse().unwrap();
let mut rng = rand::thread_rng();
let title_fmt = TITLES[rng.gen_range(0, TITLES.len())];
let title = str::replace(title_fmt, "{}", "CódigoComentado");
let post = get_post(id);
context.insert("title", &title);
context.insert("post", &post);
Template::render("posts", context)
}
fn main() {
rocket::ignite()
.attach(Template::fairing())
.mount("/", routes![index])
.mount("/", routes![index, show_post])
.mount("/static", StaticFiles::from("static"))
.launch();
}