【发布时间】:2013-09-02 21:44:23
【问题描述】:
在使用 _.template 从 Backbone.js 传递值后,我目前正在渲染 Jade 模板。我可以访问直接呈现为的任何内容:
// Jade
{{ variable }}
但我无法使用:
// Jade
each item in variable
// exception: variable is not defined
因此,例如在下面的代码中,我试图发送一个资源对象,我可以使用每个对象进行迭代,但我似乎根本无法访问它,除非它被标记为 {{ resources }},但是那么我似乎无法在 Jade 中对它进行迭代。
Backbone.js:
render: function() {
this.$el.append( this.todoTpl({
// data
resources: this.collection.data.attributes.resources,
})
);
return this;
}
玉:
if(typeof resources !== "undefined")
each key, value in resources
div.dev
p= value
p= key
从不显示任何内容。 如果我使用 {{ resources }},我可以将 [Object, Object] 渲染到 HTML。
我尝试过使用 locals.resources 等,但我似乎无法确定这一点,而且它似乎应该是一些愚蠢而简单的东西。
TL;DR:我如何设置一个变量,以便 Jade 方法可以访问它,而不仅仅是通过 {{ variable }} 呈现为文本?
谢谢!
更新: 为我的收藏发布附加代码:
var ProjectDataCollection = Backbone.Collection.extend({
defaults: {
versionOne: "",
eCM: "",
bugzilla: "",
teamCity: "",
appData: "",
data: "",
},
model: ProjectModel,
url: '/data',
initialize: function(models, options) {
var id = options.id || [];
if (id > 0) {
this.fetchData(id);
}
console.log("A new collection has been created.");
},
fetchData: function(id) {
// Save a reference to the existing url
var baseUrl = this.url;
// Assign our batch url to the 'url' property and call the server
this.url += '/' + id;
this.fetch({
success: function(collection, response) {
collection.appData = new AppData(response.details);
collection.bugzilla = new Bugzilla(response.apis.bugzilla);
collection.versionone = new VersionOne(response.apis.versionone);
collection.trigger('change');
},
error: function() {
console.log("fail");
}
});
// Restore the 'url' property
this.url = baseUrl;
}
});
我避免发布所有这些主要是为了让我的问题保持简单。如果我遗漏了太多内容,我深表歉意!我也知道由于我对 Backbone 的缺乏经验,我在这里做了一些可怕的事情 :)
更新分辨率:
回答几个问题:我使用 Jade 和 Underscore 是因为用于 HTML 的 Jade 模板既美观又简洁。 Backbone 使用 Underscore 将数据传递到我用 Jade 渲染的 JS 模板中。虽然我没有看到很多人在网上这样做,但在一些帖子中,其他人更喜欢这种安排。
user1737909 的 cmets 帮助我找到了解决方案。使用 _.template 时,我将覆盖传递给 templateSettings 全局以利用 {{ }} 进行插值(我使用过的另一个模板引擎的保留)。下划线会以这种方式打印出直接的值,但它不会处理脚本,例如:
{{ _.each(list, function() {} }}
一旦我删除了我的覆盖设置:
<% _.each(list, function() {} %>
非常高兴并且工作完美。虽然使用两个模板引擎似乎很奇怪,但我不得不说 Jade 非常好,享受它的语法仍然值得:)
感谢您的反馈!
【问题讨论】:
-
你为什么同时使用jade和_.template???它们是替代品。两者都使用很奇怪。
标签: javascript backbone.js pug