eggmatters
eggmatters

Reputation: 1140

How can Handlebars render a flat JSON object

This question should be relatively simple. I have a collection of flat objects of key-value pairs I would like to render. For my example, I receive a collection of states defined like this:

var an_array=[
{AK:"Alaska"},
{WA:"Washington"},    
];

And I compile a Handlebars template thus:

var source   = $("#src").html();
var template = Handlebars.compile(source);
$("body").append( template(an_array) );

The template is not rendering the array:

<script type='text/template' id='src'>
<ul>
{{#each .}}
<li>{{@key}}</li>
{{/each}}
</ul>    
</script>

From www.handlebars.js:

For object iteration, use {{@key}} instead:

That's pretty much it. I've written a jsfiddle here: http://jsfiddle.net/eggmatters/yMasE/

I have several large arrays being returned from the server and I would like to render those objects as they are instead of reformatting them etc.

Upvotes: 1

Views: 3326

Answers (1)

Jeff Escalante
Jeff Escalante

Reputation: 3157

So for this particular situation, the smoothest way is probably to write a custom iterator. I updated your fiddle, fixed a couple of breaking errors, and added a list iteration helper that achieves what you are after.

Handlebars.registerHelper('list', function(ctx, opts) {
  var res = ''
  ctx.forEach(function(obj){
    var key = Object.keys(obj);
    var data = {key: key, val: obj[key]}
    res += opts.fn(obj, { data: data });
  });
  return res;
});

var an_array = [{AK:"Alaska"}, {WA:"Washington"}];
var source = $("#src").html();
var template = Handlebars.compile(source);
$("body").append(template(an_array));

Using this iterator, you could update your template to look like this and it will render correctly:

<ul>
  {{#list .}}
    <li>{{@key}}: {{@val}}</li>
  {{/list}}
</ul>

Live Example: http://jsfiddle.net/yMasE/2/

The way that custom iterators work in handlebars is a little confusing, but you can find some details here: http://handlebarsjs.com/block_helpers.html

Hope this helps!

Upvotes: 3

Related Questions