I have an app in Node.js using Expressjs and Handlebars as the template engine.
Expressjs uses layouts and then renders views. The layout (layout.hbs) looks like th
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) Register a new helper called "template" on server configuration
var hbs = require('hbs');
hbs.registerHelper("template", function(key, options){
var source = options.fn().replace("\\{{", "{{");
var ret =
'';
return ret;
});
2) Use it anywhere in your client-side webpage (with \{{ escape for client-side parameters)
{{#template "myTemplate"}}
Hello \{{this.name}}!
{{/template}}
(the server will precompile it in something like this)
3) Simply call the function where you need it in client-side javascript
var generatedHtml = myTemplate("world"); // = Hello world!
$("#myDiv").html(generatedHtml); // or whatever