Skip to content

Commit 28d7db0

Browse files
committed
(feat) add preprocessfn to registry [#387]
1 parent 45c939d commit 28d7db0

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

src/registry.rs

+30
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,11 @@ use crate::helpers::scripting::ScriptHelper;
3636
/// parameters (and because traits cannot be aliased using `type`).
3737
pub type EscapeFn = Box<dyn Fn(&str) -> String + Send + Sync>;
3838

39+
/// A template preprocess function that takes template string and its name (if given)
40+
/// as input and returns processed template string. The processed string will be registered
41+
/// into registry instead of the original.
42+
pub type PreprocessFn = Box<dyn Fn(&str, Option<&str>) -> String>;
43+
3944
/// The default *escape fn* replaces the characters `&"<>`
4045
/// with the equivalent html / xml entities.
4146
pub fn html_escape(data: &str) -> String {
@@ -56,6 +61,7 @@ pub struct Registry<'reg> {
5661
helpers: HashMap<String, Box<dyn HelperDef + Send + Sync + 'reg>>,
5762
decorators: HashMap<String, Box<dyn DecoratorDef + Send + Sync + 'reg>>,
5863
escape_fn: EscapeFn,
64+
preprocess_fn: Option<PreprocessFn>,
5965
source_map: bool,
6066
strict_mode: bool,
6167
#[cfg(feature = "script_helper")]
@@ -106,6 +112,7 @@ impl<'reg> Registry<'reg> {
106112
helpers: HashMap::new(),
107113
decorators: HashMap::new(),
108114
escape_fn: Box::new(html_escape),
115+
preprocess_fn: None,
109116
source_map: true,
110117
strict_mode: false,
111118
#[cfg(feature = "script_helper")]
@@ -382,6 +389,29 @@ impl<'reg> Registry<'reg> {
382389
&*self.escape_fn
383390
}
384391

392+
/// Register a *preprocess fn* to transform all template string.
393+
///
394+
/// The template content and its name (if given) is provided for this function.
395+
/// The function has to return the transformed content which will be registered
396+
/// into handlebars registry eventually.
397+
pub fn register_preprocess_fn<F: 'static + Fn(&str, Option<&str>) -> String + Send + Sync>(
398+
&mut self,
399+
preprocess_fn: F,
400+
) {
401+
self.preprocess_fn = Some(Box::new(preprocess_fn));
402+
}
403+
404+
/// Remove the template preprocessor. Note that this won't affect template that
405+
/// has been registered.
406+
pub fn unregister_preprocess_fn(&mut self) {
407+
self.preprocess_fn = None;
408+
}
409+
410+
/// Get a reference to *preprocess fn*
411+
pub fn get_preprocess_fn(&self) -> Option<&dyn Fn(&str, Option<&str>) -> String> {
412+
self.preprocess_fn.as_ref().map(|b| b.as_ref())
413+
}
414+
385415
/// Return `true` if a template is registered for the given name
386416
pub fn has_template(&self, name: &str) -> bool {
387417
self.get_template(name).is_some()

0 commit comments

Comments
 (0)