将变量从 backbone 视图发送到 jade 模板
Send variable from backbone view to jade template
我的 index.jade 中有以下模板:
....
<script type="text/template" id="sample-template">
a(href="<%= link.href %>") <%= link.title %>
</script>
....
我的 backbone 视图中有以下代码,它将一个名为 link
的变量发送到 index.jade。
....
var SampleView = Backbone.View.extend({
template: _.template($('#sample-template').html()),
render: function() {
this.$el.append(this.template({
link: this.model.toJSON()
}));
return this;
}
});
....
现在,当我渲染该模板时,我得到以下输出:
<a href="<%= link.href %>"> sample link
你看,我得到了 title
变量的正确输出。但问题在于 href
。它不打印 link.href
.
的值
终于发现问题所在了。因为 jade
是一个与 node
一起工作的模板引擎(实际上在服务器端),它在客户端使用方面缺乏支持。所以当你编译一个带有下划线_.template
函数的jade
模板时,你不能期待一个函数式模板文件。
但是还有另一种方法可以将变量从 backbone 视图发送到 jade 模板。您可以创建一个辅助函数,在 jade 模板中打印您想要的任何内容。
....
var SampleView = Backbone.View.extend({
template: _.template($('#sample-template').html()),
render: function() {
this.$el.append(this.template({
link: this.model.toJSON(),
ahref: this.ahref
}));
return this;
},
ahref: function( href, title ) {
return '<a href=' + href + '>' + title + '</a>';
}
});
....
然后我需要将 link
辅助函数传递到 jade 模板中。
....
<script type="text/template" id="sample-template">
ahref(link.href, link.title);
</script>
....
我的 index.jade 中有以下模板:
....
<script type="text/template" id="sample-template">
a(href="<%= link.href %>") <%= link.title %>
</script>
....
我的 backbone 视图中有以下代码,它将一个名为 link
的变量发送到 index.jade。
....
var SampleView = Backbone.View.extend({
template: _.template($('#sample-template').html()),
render: function() {
this.$el.append(this.template({
link: this.model.toJSON()
}));
return this;
}
});
....
现在,当我渲染该模板时,我得到以下输出:
<a href="<%= link.href %>"> sample link
你看,我得到了 title
变量的正确输出。但问题在于 href
。它不打印 link.href
.
终于发现问题所在了。因为 jade
是一个与 node
一起工作的模板引擎(实际上在服务器端),它在客户端使用方面缺乏支持。所以当你编译一个带有下划线_.template
函数的jade
模板时,你不能期待一个函数式模板文件。
但是还有另一种方法可以将变量从 backbone 视图发送到 jade 模板。您可以创建一个辅助函数,在 jade 模板中打印您想要的任何内容。
....
var SampleView = Backbone.View.extend({
template: _.template($('#sample-template').html()),
render: function() {
this.$el.append(this.template({
link: this.model.toJSON(),
ahref: this.ahref
}));
return this;
},
ahref: function( href, title ) {
return '<a href=' + href + '>' + title + '</a>';
}
});
....
然后我需要将 link
辅助函数传递到 jade 模板中。
....
<script type="text/template" id="sample-template">
ahref(link.href, link.title);
</script>
....