Tidy up handlebars example.

This commit is contained in:
Sergio Benitez 2017-12-28 20:52:03 -08:00
parent f9f1ed75cd
commit 9f9971f4cf
2 changed files with 16 additions and 13 deletions

View File

@ -9,8 +9,8 @@ extern crate rocket;
use rocket::Request; use rocket::Request;
use rocket::response::Redirect; use rocket::response::Redirect;
use rocket_contrib::Template; use rocket_contrib::{Template, handlebars};
use rocket_contrib::handlebars::{Helper, Handlebars, RenderContext, RenderError, JsonRender}; use handlebars::{Helper, Handlebars, RenderContext, RenderError, JsonRender};
#[derive(Serialize)] #[derive(Serialize)]
struct TemplateContext { struct TemplateContext {
@ -27,7 +27,7 @@ fn index() -> Redirect {
fn get(name: String) -> Template { fn get(name: String) -> Template {
let context = TemplateContext { let context = TemplateContext {
name: name, name: name,
items: vec!["One", "Two", "Three"].iter().map(|s| s.to_string()).collect() items: vec!["One".into(), "Two".into(), "Three".into()],
}; };
Template::render("index", &context) Template::render("index", &context)
@ -40,20 +40,23 @@ fn not_found(req: &Request) -> Template {
Template::render("error/404", &map) Template::render("error/404", &map)
} }
fn echo_helper(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> { type HelperResult = Result<(), RenderError>;
if let Some(p0) = h.param(0) {
rc.writer.write(p0.value().render().into_bytes().as_ref())?; fn wow_helper(h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> HelperResult {
}; if let Some(param) = h.param(0) {
write!(rc.writer, "<b><i>{}</i></b>", param.value().render())?;
}
Ok(()) Ok(())
} }
fn rocket() -> rocket::Rocket { fn rocket() -> rocket::Rocket {
rocket::ignite() rocket::ignite()
.mount("/", routes![index, get]) .mount("/", routes![index, get])
.attach(Template::custom(|engines| {
engines.handlebars.register_helper("echo", Box::new(echo_helper));
}))
.catch(catchers![not_found]) .catch(catchers![not_found])
.attach(Template::custom(|engines| {
engines.handlebars.register_helper("wow", Box::new(wow_helper));
}))
} }
fn main() { fn main() {

View File

@ -13,7 +13,7 @@
{{/each}} {{/each}}
</ul> </ul>
<p>Try going to <a href="/hello/YourName">/hello/YourName</a></p> <p>Try going to <a href="/hello/YourName">/hello/YourName</a>.</p>
<p>You can define custom helper like <b>{{echo "this"}}</b>.</p> <p>Also, check {{ wow "this" }} (custom helper) out!</p>
</body> </body>
</html> </html>