2017-05-27 72 views
1

我有一個骨幹模型返回是這樣的:如何評估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> 
+1

您可以註冊CONCAT幫手像[this](https://gist.github.com/adg29/f312d6fab93652944a8a1026142491b1)例如 – clonq

回答

1

一個最好的辦法既從執行和良好設計的角度可能會在您的模型上有功能

model.currentLanguage =() => model[model.language] 

然後你可以在你的視圖中使用它

<h1>{{currentLanguage().title}}</h1> 
<h2>{{currentLanguage().subtitle}}</h2> 
1

當渲染時,只需使用正確的語言數據作爲模板的上下文。

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> 
0

嘗試使用在車把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}}