Mustache.js - display key instead of value

…衆ロ難τιáo~ 提交于 2019-12-17 20:47:49

问题


I am using this data here: http://pastie.org/3231052 - How can I display the key instead of the value using Mustache or Handlebars?

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

回答1:


If you want to display key-value pairs, you can write a helper in 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>

EDIT

Seems like this isn't quite what you want, but it's possible to come up with a helper that will do the trick.




回答2:


I modified the previous response using Handlebars to handle objects key value pair. It is as simple as just doing the following:

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

I put an example on Fiddle, hope it helps someone out there. Please note this implementation depends on Handlebars

Mustache Attribute addition.



来源:https://stackoverflow.com/questions/8961939/mustache-js-display-key-instead-of-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!