Allow registration of handlebars helpers

This commit is contained in:
Philip Whineray 2016-12-26 14:59:05 +00:00
parent 71419933a5
commit 82519d56bc
3 changed files with 43 additions and 0 deletions

View File

@ -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;

View File

@ -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<Handlebars> = RwLock::new(Handlebars::new());
@ -33,3 +34,39 @@ pub fn render<T>(name: &str, info: &TemplateInfo, context: &T) -> Option<String>
}
}
}
/// 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<HelperDef + 'static>)
-> Option<Box<HelperDef + 'static>> {
let r = HANDLEBARS.write().unwrap().register_helper(name, def);
r
}

View File

@ -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;