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

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

问题描述

我正在使用 PHP 后端、Backbone.js 和 Handlebars.js.我的javascript请求数据,成功返回JSON数据(json_encode).

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 不喜欢"并且没有显示.看看下面的代码.

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 需要上下文的对象因为它使用上下文作为模板值的简单查找表.因此,您需要将对象 ({ ... }) 传递给 template(),而不是数组 ([ ... ]).

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 的 PHP 以发送 JSONified 对象(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]));

如果你有这个文字代码:

If you have this literal code:

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

在您的 JavaScript 文件中,您必须了解生成该代码的内容并修复它.如果您的 Backbone 视图中确实嵌入了类似的文字数据,那么您可能没有正确使用 Backbone,您的模板数据应该来自 Backbone 模型.

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.

如果您从 Backbone 模型中获取 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天全站免登陆