From 82519d56bc51d258858d272f931c20beedb70c26 Mon Sep 17 00:00:00 2001 From: Philip Whineray Date: Mon, 26 Dec 2016 14:59:05 +0000 Subject: [PATCH] Allow registration of handlebars helpers --- contrib/src/lib.rs | 3 ++ contrib/src/templates/handlebars_templates.rs | 37 +++++++++++++++++++ contrib/src/templates/mod.rs | 3 ++ 3 files changed, 43 insertions(+) diff --git a/contrib/src/lib.rs b/contrib/src/lib.rs index 8d06d2d4..093ee369 100644 --- a/contrib/src/lib.rs +++ b/contrib/src/lib.rs @@ -48,3 +48,6 @@ pub use json::JSON; #[cfg(feature = "templates")] pub use templates::Template; + +#[cfg(feature = "handlebars_templates")] +pub use templates::register_handlebars_helper; diff --git a/contrib/src/templates/handlebars_templates.rs b/contrib/src/templates/handlebars_templates.rs index b750e7e1..9b5ea6d4 100644 --- a/contrib/src/templates/handlebars_templates.rs +++ b/contrib/src/templates/handlebars_templates.rs @@ -6,6 +6,7 @@ use super::serde::Serialize; use super::TemplateInfo; use self::handlebars::Handlebars; +use self::handlebars::HelperDef; lazy_static! { static ref HANDLEBARS: RwLock = RwLock::new(Handlebars::new()); @@ -33,3 +34,39 @@ pub fn render(name: &str, info: &TemplateInfo, context: &T) -> Option } } } + +/// Registers a handlebars helper for use with `.hbs` templates +/// +/// Define a helper function, exactly as you would for handlebars-rust: +/// +/// ```rust,ignore +/// # use handlebars::Context; +/// # use handlebars::Helper; +/// # use handlebars::Handlebars; +/// # use handlebars::RenderContext; +/// # use handlebars::RenderError; +/// fn hex_helper (_: &Context, h: &Helper, _: &Handlebars, rc: &mut RenderContext) -> Result<(), RenderError> { +/// // just for example, add error check for unwrap +/// let param = h.param(0).unwrap().value(); +/// let rendered = format!("0x{:x}", param.as_u64().unwrap()); +/// try!(rc.writer.write(rendered.into_bytes().as_ref())); +/// Ok(()) +/// } +/// ``` +/// +/// Register it before you ignite (replaces handlebars.register_helper): +/// +/// ```rust,ignore +/// rocket_contrib::register_handlebars_helper("hex", Box::new(hex_helper)); +/// ``` +/// +/// Use the helper in your template, as usual: +/// ``` +/// {{hex my_value}} +/// ``` +pub fn register_handlebars_helper(name: &str, + def: Box) + -> Option> { + let r = HANDLEBARS.write().unwrap().register_helper(name, def); + r +} diff --git a/contrib/src/templates/mod.rs b/contrib/src/templates/mod.rs index 1280168d..b876719f 100644 --- a/contrib/src/templates/mod.rs +++ b/contrib/src/templates/mod.rs @@ -8,6 +8,9 @@ mod tera_templates; #[cfg(feature = "handlebars_templates")] mod handlebars_templates; +#[cfg(feature = "handlebars_templates")] +pub use self::handlebars_templates::register_handlebars_helper; + #[macro_use] mod macros; use self::serde::Serialize;