Rocket/examples/handlebars_templates/src/main.rs

85 lines
1.9 KiB
Rust
Raw Normal View History

#![feature(plugin, decl_macro)]
2016-10-04 00:56:43 +00:00
#![plugin(rocket_codegen)]
extern crate rocket_contrib;
extern crate rocket;
2016-10-04 00:56:43 +00:00
#[macro_use] extern crate serde_derive;
#[cfg(test)] mod tests;
use rocket::Request;
use rocket::response::Redirect;
2017-12-29 04:52:03 +00:00
use rocket_contrib::{Template, handlebars};
2018-07-02 21:11:09 +00:00
2018-07-22 09:25:55 +00:00
use handlebars::{Helper, Handlebars, Context, RenderContext, Output, HelperResult, JsonRender};
#[derive(Serialize)]
struct TemplateContext {
2018-07-02 21:11:09 +00:00
title: &'static str,
name: Option<String>,
items: Vec<&'static str>,
// This key tells handlebars which template is the parent.
parent: &'static str,
}
#[get("/")]
fn index() -> Redirect {
Redirect::to("/hello/Unknown")
}
#[get("/hello/<name>")]
2018-03-24 15:43:06 +00:00
fn hello(name: String) -> Template {
2018-07-02 21:11:09 +00:00
Template::render("index", &TemplateContext {
title: "Hello",
name: Some(name),
items: vec!["One", "Two", "Three"],
parent: "layout",
})
2018-03-24 15:43:06 +00:00
}
#[get("/about")]
fn about() -> Template {
2018-07-02 21:11:09 +00:00
Template::render("about", &TemplateContext {
title: "About",
name: None,
items: vec!["Four", "Five", "Six"],
parent: "layout",
})
}
#[catch(404)]
fn not_found(req: &Request) -> Template {
let mut map = std::collections::HashMap::new();
map.insert("path", req.uri().as_str());
Template::render("error/404", &map)
}
2018-07-22 09:25:55 +00:00
fn wow_helper(
h: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
out: &mut Output
) -> HelperResult {
2017-12-29 04:52:03 +00:00
if let Some(param) = h.param(0) {
2018-07-22 09:25:55 +00:00
out.write("<b><i>")?;
out.write(&param.value().render())?;
out.write("</b></i>")?;
2017-12-29 04:52:03 +00:00
}
Ok(())
}
fn rocket() -> rocket::Rocket {
rocket::ignite()
2018-03-24 15:43:06 +00:00
.mount("/", routes![index, hello, about])
2017-12-29 04:52:03 +00:00
.catch(catchers![not_found])
.attach(Template::custom(|engines| {
2017-12-29 04:52:03 +00:00
engines.handlebars.register_helper("wow", Box::new(wow_helper));
}))
}
fn main() {
rocket().launch();
}