Question

I am using PHP-backend, Backbone.js and Handlebars.js. My javascript requests for data, and JSON data is returned successfully (json_encode).

When I give this JSON data to the handlebars template, it is not displaying. I realised the square brackets in front and at the back of my JSON object are 'disliked' by Handlebars.js and not being displayed. Take a look at the code below.

var ArticleListView = Backbone.View.extend(
{
  el: $('#main'),
  render: function()
  {
    var template = Handlebars.compile($("#articles_hb").html());
    $(this.el).html(template([{"articles":[{"title" : "1"}, {"title" : "2"}]}]));
    return this;    
  }
});

Now, if I take the brackets out, it works fine. What's going on? Why are the square brackets there in the first place? How do I get rid of them?

Was it helpful?

Solution

Handlebars wants an object for the context as it uses the context as a simple lookup table for template values. So you need to pass an object ({ ... }) to template(), not an array ([ ... ]).

Someone is give you a one element array that contains the context object you need. Either fix the PHP that is producing the JSON to send a JSONified object (associative array in PHP terms) without the array wrapper or strip off the array in the client code with something like this:

$(this.el).html(template(context[0]));

If you have this literal code:

$(this.el).html(template([{"articles":[{"title" : "1"}, {"title" : "2"}]}]));

in your JavaScript file then you have to what is generating that code and fix it. If you do have literal data like that embedded in your Backbone view then you're probably not using Backbone correctly, the data for your template should probably be coming from a Backbone model.

If you're getting that JSON from a Backbone model then I'd guess that you're calling toJSON on a collection (which returns an array) rather than a single model where toJSON should give you a JavaScript object.

OTHER TIPS

It's perfectly reasonable to call Handlebars to loop through the output of a collection. Also an array is not a bad design decision for data handling in views.

Handlebars has a special syntax for dealing with numeric or symbol identifiers, as described here. So, the more correct answer is that Handlebars can access arrays in templates like this:

{{people.attributes.[0]}} // akin to people.attributes[0]
{{people.attributes.[1]}} // akin to people.attributes[1]

Input: mails:[{headers: {subject: ["Hello Darling", "...another"]}}, ...more ]

<ul>
  {{#each mails}}
    <li>.
        {{headers.subject.[0]}}
    </li>
  {{/each}}
</ul>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top