我在这里使用这些数据:
http://pastie.org/3231052 – 如何使用Mustache或Handlebars显示键而不是值?
[{"interval":"2012-01-21","advertiser":"Advertisers 1","offer":"Life Insurance","cost_type":"CPA","revenue_type":"CPA",... etc ... }]
解决方法
如果要显示键值对,可以在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","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>
编辑@H_404_13@