Handlebars.js不喜欢在前面的方括号 [英] Handlebars.js doesn't like square brackets in the front

查看:181
本文介绍了Handlebars.js不喜欢在前面的方括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用PHP的后端,Backbone.js的和Handlebars.js。我对数据的JavaScript请求和JSON数据成功返回(json_en code)。

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

当我给这个JSON数据车把模板,它不显示。我认识的方括号在前面,并在我的JSON对象回来Handlebars.js而不是被'不喜欢'被显示。看看下面的code。

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?

推荐答案

把手想要的对象为上下文因为它使用的上下文作为模板值的简单查找表。所以,你需要传递一个对象( {...} )以模板(),而不是一个数组( [...] )。

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 ([ ... ]).

有人是给你一个包含你所需要的上下文对象一个元素的数组。要么修复正在生产JSON发送JSONified对象(在PHP术语关联数组)未经阵列封装或剥离在客户端code数组像这样的PHP:

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]));

如果你有这样的文字code:

If you have this literal code:

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

在你的JavaScript文件,那么你有什么是产生了code和修复它。如果您有这样的嵌入到您的骨干视图字面数据,那么你很可能无法正常使用骨干,为你的模板中的数据或许应该从骨干模型来了。

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.

如果你得到了JSON从骨干网的模型,然后我猜你调用的 的toJSON 对集合(它返回一个数组),而不是单一的模型,其中的 的toJSON 应该给你一个JavaScript对象。

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.

这篇关于Handlebars.js不喜欢在前面的方括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆