I didn t like the precompilation solution (because I want to define templates in the same file where I will use them) nor the naive {{
escape solution (because it needs the full Handlebars compiler and more javascript code) so I came up with an hybrid solution that uses Handlebars helpers:
(1) 在服务器组合中登记一个称为“模版”的新助手
var hbs = require( hbs );
hbs.registerHelper("template", function(key, options){
var source = options.fn().replace("\{{", "{{");
var ret =
<script>
+
key + = function(opt){
+
return Handlebars.template( + hbs.handlebars.precompile(source) + )(opt);
+
}
+
</script> ;
return ret;
});
2) Use it anywhere in your client-side webpage (with {{
escape for client-side parameters)
{{#template "myTemplate"}}
<div>
<p>Hello {{this.name}}!</p>
</div>
{{/template}}
(the server will precompile it in something like this)
<script>
myTemplate = function(opt){
return Handlebars.template(/* HBS PRECOMPILATED FUNCTION */)(opt);
}
</script>
3) Simply call the function where you need it in client-side javascript
var generatedHtml = myTemplate("world"); // = <div><p>Hello world!</p></div>
$("#myDiv").html(generatedHtml); // or whatever