当模板中显示的数据是国际化文本或模型属性时,呈现模板是小菜一碟,但当谈到在一个模板中同时呈现这两者时,我似乎找不到一个干净的解决方案。
作为引用,我通过 Require.js 的 i18n 插件使用 i18n。
假设我有一个简单的模板:
<h3>{{displayText.load}} #{{id}}</h3>
<h4 id="loading-load-data">{{displayText.loadingLoadData}}...</h4>
displayText
对象表示 i18n 文本,而 id
项表示 Backbone 模型属性。
在 View 上使用 Backbone 的 template
属性,我可以执行以下操作以呈现带有 i18n 文本但没有模型属性数据的模板:
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
});
但是,一旦我还想显示模型数据,这就不再有效了,主要是因为 this
在模板属性中未定义(因此我无法引用 this.model .attributes
),看来我必须回过头来覆盖 render()
方法,将 i18n 对象和模型属性都传递给模板,如下所示:
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()
的默认处理,只使用模板属性来呈现 i18n 文本和模型数据。这可能吗?
奖励:假设我必须覆盖 render()
,我注意到在这样做时,this.ui
属性,在 Marionette Views 上提供,不再将每个项目包装为 jQuery 对象。这意味着:
this.ui.loadingNotification.show();
停止运行,抛出 Uncaught TypeError: Object #loading-load-data has no method 'show'
。这是为什么,如何恢复正确的 this.ui
jQuery 包装功能?
编辑:解决了BONUS;只需在 render()
方法中调用 this.bindUIElements()
即可将元素正确绑定(bind)到 ui
哈希。请参阅上面的 render()
示例。
最佳答案
已解决:所以答案非常简单。事实证明,当用作函数时,您可以将参数传递给模板:属性,并且此参数表示与该 View /模板关联的模型:
template: function (model) {
var templateParams = _.extend({}, model, localizedText),
renderedTemplate = Handlebars.compileClean(template);
return renderedTemplate(templateParams);
},
render()
方法不再需要重写,i18n 文本和模型数据都可以按预期呈现到模板中。
关于javascript - 如何在 Backbone.Marionette View 中最轻松地呈现 i18n 文本和模型属性(使用 Handlebars 模板),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13710708/