如何评估Handlebars表达式?
问题描述:
我有一个骨干模型返回是这样的:如何评估Handlebars表达式?
{
language: "us",
us: {
title: "Gigs",
subtitle: "Stay tune to my upcoming gigs"
},
br: {
title: "Shows",
subtitle: "Fique ligado na minha agenda"
}
}
的language
被动态地更新,因此它会确定的哪个对象我要打印,使用把手。通常我会做:
<h1>{{title}}</h1>
<h2>{{subtitle}}</h2>
但我需要做一些CONCAT的:
<h1>{{language.title}}</h1>
<h2>{{language.subtitle}}</h2>
当然,这是行不通的。这是我的问题:我怎样才能使表达动态concat?
因此,如果语言是"us"
,它调用:
<h1>{{us.language.title}}</h1>
<h2>{{us.language.subtitle}}</h2>
而如果它的"br"
,它要求:
<h1>{{br.language.title}}</h1>
<h2>{{br.language.subtitle}}</h2>
答
一个最好的办法既从执行和良好设计的角度可能会在您的模型上有功能
model.currentLanguage =() => model[model.language]
然后你可以在你的视图中使用它
<h1>{{currentLanguage().title}}</h1>
<h2>{{currentLanguage().subtitle}}</h2>
答
当渲染时,只需使用正确的语言数据作为模板的上下文。
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>
答
尝试使用在车把with
帮手沿要么喜欢@George莫尔功能建议或局部功能,同时传递参数模板
假设我们有一个函数返回当前语言
var lang = model[String(model.language)]; // or this, depending on where your model lives
你会通过lang
变量在你的模板(取决于你如何实现你的应用程序的方法有很多把手模板)
你必须
{{#with lang}}
<h1>{{title}}</h1>
<h2>{{subtitle}}</h2>
{{/with}}
您可以注册CONCAT帮手像[this](https://gist.github.com/adg29/f312d6fab93652944a8a1026142491b1)例如 – clonq