Handlebarsjs 遗留表达式

Handlebarsjs left behind expression

我正在寻找如何使用 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>

为了重用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"
}));
  1. Expressions are helpers

    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" [...]

  2. 当一个助手缺失时,调用一个internal helper named helperMissing来替换缺失的表达式

  3. 您可以通过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
    }
});

http://jsfiddle.net/jrtrvmd4/3/