node.js - Handlebarsjs 留下的表情

标签 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>

最佳答案

  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/

关于node.js - Handlebarsjs 留下的表情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430200/

相关文章:

node.js - 如何以 Angular 显示 Node 服务器上保存的图像

Javascript/Node.js 异步循环

javascript - 在 JavaScript 中解压缩 Gzip 缓冲区

node.js - Nodejs 请求知道何时重试

node.js - 将对象传递给 Handlebars 后,如何在脚本标记中访问该对象?

mongodb - 查看 Handlebars 循环 MeteorJS 中的上一个项目

javascript - 将 Handlebars 数据发送到客户端 javascript

Ember.js:将模型传递到 View 中

node.js - Node 入门书籍 - requestHandlers

javascript - 动态渲染模板,无需重新加载页面