我有一个骨干模型返回这样的东西:
{
language: "us",
us: {
title: "Gigs",
subtitle: "Stay tune to my upcoming gigs"
},
br: {
title: "Shows",
subtitle: "Fique ligado na minha agenda"
}
}
language
正在动态更新,因此它将使用Handlebars确定我要打印的对象。通常我会这样做:
<h1>{{title}}</h1>
<h2>{{subtitle}}</h2>
但我需要做一些结论:
<h1>{{language.title}}</h1>
<h2>{{language.subtitle}}</h2>
当然这不起作用。这就是我的问题:如何让表达式动态连接?
因此,如果语言为"us"
,则会调用:
<h1>{{us.language.title}}</h1>
<h2>{{us.language.subtitle}}</h2>
如果是"br"
,则会调用:
<h1>{{br.language.title}}</h1>
<h2>{{br.language.subtitle}}</h2>
答案 0 :(得分:2)
从执行和良好的设计角度来看,最好的方法之一可能是在模型上有一个功能
model.currentLanguage = () => model[model.language]
然后你可以在你的观点中使用它
<h1>{{currentLanguage().title}}</h1>
<h2>{{currentLanguage().subtitle}}</h2>
答案 1 :(得分:2)
渲染时,只需使用正确的语言数据作为模板的上下文。
this.template(this.model.get(this.model.get('language')));
您也可以在模型上创建一个函数,与George mentioned不同,而不是直接在上下文中。
var LanguageModel = Backbone.Model.extend({
/**
* Get the translated data for the currently set language.
* @param {string} [lang] optional language string to override the default one
* @return {Object} the language translation object.
*/
getLanguageData: function(lang) {
return this.get(lang || this.get('language'));
},
//...
});
现在,您只需调用该函数即可获得正确的对象。
this.template(this.model.getLanguageData());
在你的模板中,没有区别:
<h1>{{title}}</h1>
<h2>{{subtitle}}</h2>
答案 2 :(得分:0)
尝试在Handlebars中使用with
帮助器以及@George Mauer建议的函数或在模板中传递参数时的本地函数
假设我们有一个返回当前语言的函数
var lang = model[String(model.language)]; // or this, depending on where your model lives
您可以在模板中传递lang
变量(取决于您在应用程序中实现Handlebars模板的方式有很多种方式)
在你的模板中
{{#with lang}}
<h1>{{title}}</h1>
<h2>{{subtitle}}</h2>
{{/with}}