当模板中显示的数据是国际化文本或模型属性时,渲染模板是小菜一碟,但当涉及到在一个模板中同时渲染这两个时,我似乎找不到干净的解决方案。
作为参考,我通过Require.js的i18n插件使用i18n。
假设我有一个简单的模板:
<h3>{{displayText.load}} #{{id}}</h3>
<h4 id="loading-load-data">{{displayText.loadingLoadData}}...</h4>
displayText
对象表示i18n文本,而id
项表示骨干模型属性。
在视图上使用Backbone的template
属性,我可以执行以下操作来呈现具有i18n文本但没有Model属性数据的模板:
return Backbone.Marionette.ItemView.extend({
template: function () {
var compiledTemplate = Handlebars.compileClean(template);
// localizedText represents the i18n localization object, using the Require.js i18n plugin
return compiledTemplate(localizedText);
},
// some more View properties and methods
});
然而,一旦我也想显示Model数据,这就不再有效了,主要是因为this
在template属性中未定义(所以我不能引用this.model.attributes
),而且我似乎不得不重写render()
方法,将i18n对象和Model属性都传递给模板,例如:
return Backbone.Marionette.ItemView.extend({
template: Handlebars.compileClean(template),
render: function() {
var templateParams = _.extend({}, this.model.attributes, localizedText),
renderedTemplate = this.template(templateParams);
this.$el.html(renderedTemplate);
this.bindUIElements();
this.delegateEvents();
return this;
}
});
我真的很想保留Marionette对render()
的默认处理,只使用template属性来呈现i18n文本和Model数据。这可能吗?
BONUS:假设我必须重写render()
,我注意到在这样做的同时,Marionette视图上提供的this.ui
属性不再将每个项包装为jQuery对象。这意味着:
this.ui.loadingNotification.show();
停止工作,抛出Uncaught TypeError: Object #loading-load-data has no method 'show'
。为什么会出现这种情况,以及如何恢复正确的this.ui
jQuery包装功能?
编辑:解决奖金;只需在render()
方法中抛出this.bindUIElements()
调用,即可将元素正确绑定到ui
散列。请参阅上面的render()
示例。
已解决:所以答案非常简单。事实证明,当用作函数时,您可以将参数传递到template:属性中,该参数表示与该视图/模板关联的模型:
template: function (model) {
var templateParams = _.extend({}, model, localizedText),
renderedTemplate = Handlebars.compileClean(template);
return renderedTemplate(templateParams);
},
render()
方法不再需要被覆盖,i18n文本和Model数据都可以按预期呈现到模板中。