最容易渲染i18n文本和模型屬性(使用Handlebars模板)當模板中顯示的數據是國際化文本或模型屬性時,呈現模板是小菜一碟,但是當它出現在一個模板中渲染BOTH,我似乎無法找到一個乾淨的解決方案。如何在Backbone.Marionette查看
僅供參考,我通過Require.js的i18n插件使用i18n。
假設我有一個簡單的模板:
<h3>{{displayText.load}} #{{id}}</h3>
<h4 id="loading-load-data">{{displayText.loadingLoadData}}...</h4>
的displayText
對象代表國際化的文本,而id
項目代表了骨幹示範屬性。
上查看使用骨幹template
財產,我可以做的,以使與國際化的文本模板下面,但沒有模型屬性數據:
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對象和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()
的默認處理位置,並且只使用模板屬性來渲染國際文本和模型數據。這可能嗎?
BONUS:假設我有重寫render()
,我注意到,雖然這樣做,this.ui
屬性,提供木偶意見,不再包裹每個項目作爲一個jQuery對象。這意味着:
this.ui.loadingNotification.show();
停止工作,拋出一個Uncaught TypeError: Object #loading-load-data has no method 'show'
。爲什麼會這樣,我該如何恢復正確的this.ui
jQuery包裝功能?
EDIT:解決了獎金;只需在render()
方法內調用this.bindUIElements()
調用以正確地將元素綁定到ui
散列。請參閱上面的render()
示例。