问题
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