Handlebars.js doesn't like square brackets in the front

跟風遠走 提交于 2019-12-01 01:39:23

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.

Mirko

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!