Mustache.js - display key instead of value

I use this data here: http://pastie.org/3231052 - How can I display a key instead of a value using Mustache or Pens?

[{"interval":"2012-01-21", "advertiser":"Advertisers 1", "offer":"Life Insurance", "cost_type":"CPA", "revenue_type":"CPA", ... etc ... }] 
+6
source share
2 answers

If you want to display key-value pairs, you can write an assistant 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

It doesn't seem like exactly what you want, but it's possible to come up with an assistant who will do the trick.

+1
source

I modified the previous answer using Handlebars to handle a pair of object key values. It is as simple as doing the following:

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

I will give an example on Fiddle, hope this helps someone there. Please note that this implementation depends on Handlebars.

Adding the Mustache attribute.

+1
source

Source: https://habr.com/ru/post/906585/


All Articles