加载模板时获取异常.下划线/骨干

lex*_*eme 3 javascript jquery requirejs backbone.js underscore.js

我收到Uncaught ReferenceError了文字:我没有定义例外

Uncaught ReferenceError: Id is not defined
(anonymous function)
y.templateunderscore-min.js:5
Backbone.View.extend.renderProductView.js:13
Backbone.View.extend.renderProductListView.js:15
Backbone.View.extend.initializeProductListView.js:4
g.Viewbackbone-min.js:34
dbackbone-min.js:38
appRouter.on.productsList.fetch.successAppRouter.js:18
f.extend.fetch.a.successbackbone-min.js:23
f.Callbacks.ojquery-1.7.2.min.js:2
f.Callbacks.p.fireWithjquery-1.7.2.min.js:2
wjquery-1.7.2.min.js:4
f.support.ajax.f.ajaxTransport.send.d
Run Code Online (Sandbox Code Playgroud)

存储在外部文件中,模板如下所示:

<a class="thumbnail" href="#/products/<%= Id %>">
    <img alt="" src="/Content/img/<%= Thumbnail %>" />
    <h5><%= Title %></h5>
    <p><%= Price %></p>
    <p><%= Details %></p>
</a>
Run Code Online (Sandbox Code Playgroud)

其对应的视图将render方法定义为:

define(['jquery', 'underscore', 'backbone', 'text!templates/product.html'], function ($, _, Backbone, productTemplate) {
var ProductView = 
...

render: function() {
    var data = {};
    var compiledTemplate = _.template(productTemplate, data);
    this.$el.append(compiledTemplate);
}
...
Run Code Online (Sandbox Code Playgroud)

是什么导致异常被抛出?谢谢!

编辑

模型定义默认值,如:

defaults: {
    Id: '00000000-0000-0000-0000-000000000000',
    Price: 0.0,
    Category: 'empty',
    Title: 'untitled',
    Details: '',
    Thumbnail: ''
}
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 6

您需要为所有插值变量提供值.像这样的模板:

<%= Id %>
Run Code Online (Sandbox Code Playgroud)

被编译成一个JavaScript函数,它是这样的包装:

with(obj || {}) {
    __p += '' + ((__t = Id) == null ? '' : __t ) + '';
}
Run Code Online (Sandbox Code Playgroud)

在控制台打开的情况下看看这个演示,你会看到.因此,您的模板函数将查找Id一个局部变量或data您传递它的对象中的键.

你的问题是你data是空的:

render: function() {
    var data = {}; // <------------------------------- Empty
    var compiledTemplate = _.template(productTemplate, data);
    this.$el.append(compiledTemplate);
}
Run Code Online (Sandbox Code Playgroud)

我想你想这样说:

_.template(productTemplate, this.model.toJSON())
Run Code Online (Sandbox Code Playgroud)

为了将模型的数据导入模板.