Handlebarsjs留下expression
我正在寻找一个解决scheme如何编译HTML模板,而不会忽略使用Handlebarsjs未填充的数据。
例如:
var Handlebars = require("handlebars"); var html = "<div>{{foo}}</div><div>{{foo2}}</div>"; html = Handlebars.compile(html)({ foo : "This is a sample" }); console.log(html);
有没有可用的编译选项,可以帮助我留下expression? 像那样:
html = Handlebars.compile(html)({ foo : "This is a sample" },{isLeftBehindEx:true}); <div>This is a sample</div><div>{{foot2}}</div>
-
expression式是帮手
这个expression的意思是“在当前上下文中查找标题属性”。 […]
实际上,这意味着“寻找一个名字的帮手,然后做上述”[…] -
当一个帮手缺失时,将调用名为
helperMissing
的内部帮助来replace缺less的expression式 -
当您执行模板来提供自定义助手时,您可以传递选项散列 。
有了这些知识,你可以用任意的string表示来replace你的缺失值:
var compiled = Handlebars.compile(html); html = compiled({ foo : "This is a sample" }, { helpers: { helperMissing: function(o) { return '{{' + o.name + '}}'; } } });
和演示http://jsfiddle.net/jrtrvmd4/
或者,如果您喜欢并将条件输出作为data
选项传递给可选标志(例如isLeftBehindEx
,则可以覆盖全局isLeftBehindEx
:
Handlebars.registerHelper('helperMissing', function(o) { return (o.data.isLeftBehindEx) ? '{{' + o.name + '}}' : ""; }); html = compiled({ foo : "This is a sample" }, { data: { isLeftBehindEx: true } });
为了重新使用Handlebarsjs的内置方法,而不重新开发不明智的代码,我仍然使用以下方法来实现我的目标…
var Handlebars = require("handlebars"); Handlebars.registerHelper('foo2', function(val, options) { return "{{"+val.name+"}}" }); var html = "<div>{{foo}}</div><div>{{foo2}}</div>"; //compile but stay behind the expressions console.log(Handlebars.compile(html)({ foo : "This is a sample" })); //compile and remove the expression as usual Handlebars.unregisterHelper('foo2'); console.log(Handlebars.compile(html)({ foo : "This is a sample" }));