【问题标题】:How to override the default output interpolation of Mustache.js, Hogan.js or Handlebars.js?如何覆盖 Mustache.js、Hogan.js 或 Handlebars.js 的默认输出插值?
【发布时间】:2013-06-16 00:25:44
【问题描述】:

有没有办法改变 Mustache、Hogan 和 Handlebars 等库的默认输出?

这是我的上下文示例:

var context = {
  primitive: 1,
  array: [1, 2, 3],
  object: new Object()
}

这就是我希望编译时的结果:

<div>
  Primitive: {{primitive}}
  Array: {{array}} should output <Array#id> instead of "1,2,3"
  Object: {{object}} should output <Object#id> instead of "[Object object]"
</div>

我知道我可以覆盖这些属性的 toString 方法,但是在插值发生之前有没有其他方法,比如回调?

【问题讨论】:

    标签: javascript templates handlebars.js mustache hogan.js


    【解决方案1】:

    可能会有 Hogan,这取决于您真正想用它做什么; https://github.com/twitter/hogan.js#features

    var text = "{{^check}}{{#i18n}}No{{/i18n}}{{/check}}";
    text +=  "{{#check}}{{#i18n}}Yes{{/i18n}}{{/check}}";
    var tree = Hogan.parse(Hogan.scan(text));
    
    // outputs "# check"
    console.log(tree[0].tag + " " + tree[0].name);
    
    // outputs "Yes"
    console.log(tree[1].nodes[0].nodes[0]);
    

    标签被解析出来,你可以随意操作树,然后在完成后编译它

    【讨论】:

      【解决方案2】:

      刚刚发现您可以覆盖 Handlebars.Utils.escapeExpression 以在模板中实现此目的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-20
        • 1970-01-01
        • 2012-04-13
        • 1970-01-01
        相关资源
        最近更新 更多