这个问题是关于模板化和本地化,使用 require.js 和通过主干.js 下划线模板。应用程序需要即时本地化。
在走上一条后来证明有问题的道路之前,有没有比我正在考虑的更好的解决方案 - 我担心重复合并和处理语言数组的速度和内存。假设是 2-3 千个语言字符串。
当前方法(可行,但看起来处理器很重):
- 使用I18N 捆绑方法,创建语言“包含”,它将基本上包含所有模板的翻译元素
- 将这个对象/元素数组与模型属性(来自主干)合并,并将合并的批次传递到下划线模板
.
define(['backbone', 'models/model', 'text!template.html', 'i18n!my/nls/translatedbits'],
function(Backbone, MyModel, TemplateText, TranslationObject) {
var View = Backbone.View.extend({
model: {},
initialize : function(params) {
this.model = new MyModel();
},
render : function(callBack) {
// Get the model attributes
var templateParams = _.clone(this.model.attributes);
// Bolt on the tranlsated elements (established from require.js I18N plugin)
templateParams.t = TranslationObject;
// Pass the lot ot the template
var template = _.template(TemplateText, this.model.attributes);
$(this.el).html( template );
return this;
}
});
return View;
}
);
然后模板将读取
<%= modelAttribute1 %> <%= t.translationString1 %>
是否有更好的解决方案或更好的模板引擎?[更适合这个目的 - mustache 可能还有其他优点,但它可以更容易地本地化,还是它可以缓存本地化结果以允许稍后传入模型属性?]
请注意,可能需要“即时”更改语言 - 这是我对 I18N 插件的另一个担忧。我最终可能会通过模板模型通过 JSON 请求获取转换,但这仍然需要对象的合并,这是我试图避免的。