@@ -36,6 +36,11 @@ use crate::helpers::scripting::ScriptHelper;
36
36
/// parameters (and because traits cannot be aliased using `type`).
37
37
pub type EscapeFn = Box < dyn Fn ( & str ) -> String + Send + Sync > ;
38
38
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
+
39
44
/// The default *escape fn* replaces the characters `&"<>`
40
45
/// with the equivalent html / xml entities.
41
46
pub fn html_escape ( data : & str ) -> String {
@@ -56,6 +61,7 @@ pub struct Registry<'reg> {
56
61
helpers : HashMap < String , Box < dyn HelperDef + Send + Sync + ' reg > > ,
57
62
decorators : HashMap < String , Box < dyn DecoratorDef + Send + Sync + ' reg > > ,
58
63
escape_fn : EscapeFn ,
64
+ preprocess_fn : Option < PreprocessFn > ,
59
65
source_map : bool ,
60
66
strict_mode : bool ,
61
67
#[ cfg( feature = "script_helper" ) ]
@@ -106,6 +112,7 @@ impl<'reg> Registry<'reg> {
106
112
helpers : HashMap :: new ( ) ,
107
113
decorators : HashMap :: new ( ) ,
108
114
escape_fn : Box :: new ( html_escape) ,
115
+ preprocess_fn : None ,
109
116
source_map : true ,
110
117
strict_mode : false ,
111
118
#[ cfg( feature = "script_helper" ) ]
@@ -382,6 +389,29 @@ impl<'reg> Registry<'reg> {
382
389
& * self . escape_fn
383
390
}
384
391
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
+
385
415
/// Return `true` if a template is registered for the given name
386
416
pub fn has_template ( & self , name : & str ) -> bool {
387
417
self . get_template ( name) . is_some ( )
0 commit comments