我正在寻找一种解决方案,如何使用 Handlebarsjs 编译 HTML 模板而不忽略未填充的数据。
例如:
var Handlebars = require("handlebars");
var html = "<div>{{foo}}</div><div>{{foo2}}</div>";
html = Handlebars.compile(html)({
foo : "This is a sample"
});
console.log(html);
是否有可用的编译选项可以帮助我留下表达式? 像这样:
html = Handlebars.compile(html)({
foo : "This is a sample"
},{isLeftBehindEx:true});
<div>This is a sample</div><div>{{foot2}}</div>
最佳答案
-
This expression means "look up the title property in the current context". [...]
Actually, it means "look for a helper named title, then do the above" [...] 当助手丢失时,internal helper named
helperMissing
被调用来替换缺失的表达式您可以通过pass an options hash when you execute your template提供自定义帮助程序。
有了这些知识,您就可以用任意字符串表示形式替换缺失值:
var compiled = Handlebars.compile(html);
html = compiled({
foo : "This is a sample"
}, {
helpers: {
helperMissing: function(o) {
return '{{' + o.name + '}}';
}
}
});
还有一个演示 http://jsfiddle.net/jrtrvmd4/
或者,如果您愿意,也可以全局覆盖 helperMissing
,并将其输出限制在作为 data
选项传递的可选标志上,例如 isLeftBehindEx
按照您的建议:
Handlebars.registerHelper('helperMissing', function(o) {
return (o.data.isLeftBehindEx) ? '{{' + o.name + '}}' : "";
});
html = compiled({
foo : "This is a sample"
}, {
data: {
isLeftBehindEx: true
}
});
关于node.js - Handlebarsjs 留下的表情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430200/