Mustache.js - 显示键而不是值

时间:2012-01-22 14:53:49

标签: jquery mustache handlebars.js

我在这里使用这些数据:http://pastie.org/3231052 - 如何使用Mustache或Handlebars显示键而不是值?

[{"interval":"2012-01-21",
  "advertiser":"Advertisers 1",
  "offer":"Life Insurance",
  "cost_type":"CPA",
  "revenue_type":"CPA",
  ... etc ...
}]

2 个答案:

答案 0 :(得分:1)

如果要显示键值对,可以在Handlebars中编写一个帮助器。

Handlebars.registerHelper('eachkeys', function(context, options) {
  var fn = options.fn, inverse = options.inverse;
  var ret = "";

  var empty = true;
  for (key in context) { empty = false; break; }

  if (!empty) {
    for (key in context) {
        ret = ret + fn({ 'key': key, 'value': context[key]});
    }
  } else {
    ret = inverse(this);
  }
  return ret;
});

$(function() {
    var data = {"interval":"2012-01-21",
      "advertiser":"Advertisers 1",
      "offer":"Life Insurance",
      "cost_type":"CPA",
      "revenue_type":"CPA"};
                
    var source   = $("#template").html();
    var template = Handlebars.compile(source);
    $('#content').html(template({'data': data}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0.beta2/handlebars.min.js"></script>
<script id="template" type="text/x-handlebars-template">
    {{#eachkeys data}}
    <li>{{this.key}} - {{this.value}}</li>
    {{/eachkeys}}
</script>
<div id="content">
</div>

修改

似乎这不是你想要的,但是有可能找到一个可以解决问题的助手。

答案 1 :(得分:1)

我使用Handlebars修改了之前的响应来处理对象键值对。它就像执行以下操作一样简单:

<script id="template" type="text/x-handlebars-template">
    {{@entries}}
    <li>{{KEY}} - {{VALUE}}</li>
    {{/entries}}
</script>
<div id="content">
</div>

我在Fiddle上放了一个例子,希望它可以帮助那些人。请注意,此实现取决于Handlebars

Mustache Attribute addition.