Handlebarsjs留下了表情

时间:2015-05-25 01:42:02

标签: node.js handlebars.js

我正在寻找一种解决方案,如何使用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>

2 个答案:

答案 0 :(得分:1)

  1. Expressions are helpers

      

    此表达式表示&#34;在当前上下文中查找title属性&#34;。 [...]
      实际上,它意味着&#34;寻找一个名为title的帮手,然后执行以上操作&#34; [...]

  2. 当缺少帮助程序时,会调用internal helper named helperMissing来替换缺少的表达式

  3. 您可以传递pass an options hash when you execute your template以提供自定义帮助程序。

  4. 有了这些知识,您可以使用任意字符串表示替换缺少的值:

    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/

答案 1 :(得分:0)

重新使用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"
}));