2014-05-02 73 views
2

我終於得到了我的PhoneGap/Backbone/Handlebars使用i18next.js本地化 - 種。i18next和handlebar的變量替換

我目前想知道如何獲得與嵌入式句柄表達式的HTML本地化與Handlebars編譯。舉個例子,我想是這樣的:

Welcome, {{this.name}}. We've been expecting you. 

變成:

Welcome, Bob. We've been expecting you. 

這還沒有定位很容易。但通過在文檔(這裏:http://i18next.com/pages/doc_templates.html)中描述的i18next模板運行...

// handlebars helper from i18next 
Handlebars.registerHelper('t', function(i18n_key) { 
    var result = i18n.t(i18n_key); 
    return new Handlebars.SafeString(result); 
}); 

//Handlebars string: 
{{t 'view.WelcomeMessage'}} 

// translation.json file 
{ "view": 
    { 
     "WelcomeMessage": "Welcome, {{this.name}}. We've been expecting you." 
    } 
} 

不幸的是,這變成本地化時,以下幾點:

Welcome, {{this.name}}. We've been expecting you. 

如何得到字符串本地化並有嵌入式表達式編譯?

回答

1

它看起來像的答案,這是在變量替換幫手TR

// handlebars helper from i18next 
Handlebars.registerHelper('tr', function(context, options) { 
    var opts = i18n.functions.extend(options.hash, context); 
    if (options.fn) opts.defaultValue = options.fn(context); 
    var result = i18n.t(opts.key, opts); 
    return new Handlebars.SafeString(result); 
}); 

// random "This" object passed in: 
var person = {name:"Bob", age:42, eyeColor:"blue"}; 

//Handlebars string: 
{{tr this key='view.WelcomeMessage'}} 

// translation.json file 
{ "view": 
    { 
    "WelcomeMessage": "Welcome, __name__. We've been expecting you." 
    } 
} 

// Output 
Welcome, Bob. We've been expecting you. 

注意,在http://i18next.com/pages/doc_templates.html給出的tr例子確實有在最後一個額外的參數。如果你想用屬性替換某個屬性,這只是必要的。

+0

我不知道如何\ _ \ _ name__被替換。幫助器調用不應該是:'{{tr key ='view.WelcomeMessage'name = this.name}}'? – gentiane

+0

@gentiane:看起來我也沒有。 'tr'助手查看通過'this'參數傳入的對象,並提取相應的屬性值。您可以通過在最後傳入另一個值來覆蓋它們,但如果對象具有用於變量替換的屬性,則不需要。我更新了我的答案,將「this」對象與「na​​me」屬性相加。 – eb1

1

對於i18next V3.2.0,其中有interpolation

的package.json |依賴/ dev依賴

"i18next": "^3.1.0", 
"babel-core": "^6.7.2", 
"babel-loader": "^6.2.4", 
"handlebars": "^4.0.2", 
"handlebars-loader": "^1.1.4", 
"webpack": "^1.12.2", 

layoutView.js |將模型數據傳遞給模板的示例:

render(){ 
    let person = {name: 'joe', age: 21}; 
     person = new Backbone.Model(person); 
    this.$el.html(template(person.toJSON())); 
    } 

layoutView.hbs |車把模板

<div>{{{ i18n 'person' name=this.name age=this.age}}}</div> 
<!-- after interpolation will read --> 
<!-- <div>joe is 21 lang: en </div> --> 

i18n.js |使用ES2015所以文件名變爲layoutView.hbs(上文)中使用的的helperName

// handlebars helper from i18next 
import i18next from 'i18next'; 
import Handlebars from 'handlebars'; 

export default function(key, options) { 
let result = i18next.t(key, options.hash); 
return new Handlebars.SafeString(result); 
}; 

translation.json |樣品在github插值

{ 
    "person": "{{name}} is {{age}} lang: en", 
    "good-bye": "good-bye: en", 
    "other": "other: en" 
} 

這個線程真的helped