【问题标题】:Handlebars breaks when passing this.item in Spine.js在 Spine.js 中传递 this.item 时车把断裂
【发布时间】:2014-05-22 05:46:07
【问题描述】:

我正在尝试实现 Spine.js 文档中给出的 Todo 示例,此处给出:http://spinejs.com/docs/example_tasks

只有我想使用 Handlebars 而不是 jQuery.tmpl。我正在使用 Handlebars 1.0.rc.1

但是,当我尝试调用时:

template: Handlebars.compile($('#history-template').html()),

render: function(){
    var t = this.template(this.item);
    this.replace(t);
    return this;
}

Handlebars 在this.template(this.item) 处抛出异常:

Uncaught TypeError: Cannot call method 'match' of undefined

在 Handlebars 词法分析器中,this._input 以未定义的形式返回。

我的模板如下:

<script id='history-template' type='text/x-handlebars-template'>
    <div class="content-inner {{#if viewed}}msg_unseen{{/if}}">                                             
        <div>{{data}}</div>
    </div>
</script>

数据:

"[{"data":"hello","id":"c-0"}]"

有什么想法吗?

【问题讨论】:

  • 以上描述中的错别字,应通过#history-template选择。但不幸的是,仍然无法使用给定的数据模型,这就是 Spine 处理其 JSON 的方式。

标签: javascript handlebars.js spine.js


【解决方案1】:

问题似乎是:

  1. ID 不匹配 - 您的模板 ID 是 history-template,但您尝试将其选为 $("#my-template)
  2. 您的数据应该写成{"data":"hello","id":"c-0"}(一个对象),不带方括号(使其成为一个数组)。

完成这两项更正后,我就可以运行您的代码了。 See here for a working demo.

var data = { data: "hello", id: "c-0" };
var template = Handlebars.compile($('#history-template').html());
var html = template(data);

(另请参阅 here 以确认 #if 逻辑是否正常工作。)


编辑

要使用数组形式的数据 -- { data: "hello", id: "c-0" } -- 据我所知,为了在 Handlebars 模板中使用它,您需要将其包装在一个对象中:

var obj = { data: "hello", id: "c-0" };
var handlebarsData = { items: obj };

这样你就可以使用 Handlebars 迭代表单{{#each items}}

{{#each items}}
    <div class="content-inner {{#if viewed}}msg_unseen{{/if}}">                                             
        <div>{{data}}</div>
    </div>
{{/each}}

Here's the updated Fiddle.

【讨论】:

  • 1) 我打错了一个字。通过#history-template 选择时,使用给定的数据模型仍然无法正常工作。 2) Spine.js 似乎以这种格式保存其 JSON,我宁愿使用相同的模型?
  • @user1868231 你看到我建议更改数据对象了吗?在您的问题中,您已将其编写为数组,但您的模板正在寻找一个对象。
  • 我做了,但正如我上面所说,Spine.js 将其数据保存在哈希数组中。我宁愿使用 Spine 提供的。
  • @amhou gotcha ...请在上面查看我的更新。如果您调整 Handlebars 模板,并将数据包装在一个对象中,那么它应该可以工作。
【解决方案2】:

您传入的数据不正确。

According to the offical handlebars documentation 数据应该作为对象传递给车把。例如:

{"foo":"bar","baz":"faz"}

使用以下模板:

<div>{{foo}}</div>
<div>{{baz}}</div>

将呈现为

<div>bar</div>
<div>faz</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-19
    • 2013-03-08
    • 1970-01-01
    • 2014-06-24
    • 2012-07-16
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多