可变替换i18next和把手

时间:2014-05-02 20:56:27

标签: handlebars.js i18next

我终于使用i18next.js让我的PhoneGap / Backbone / Handlebars本地化了。

我目前想知道如何使用嵌入式把手表达式来获取带有Handlebars本地化的html。举个例子,我想要这样的东西:

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

变成:

Welcome, Bob. We've been expecting you.

没有本地化,这很容易。但请浏览文档中描述的i18next模板(此处:http://i18next.com/pages/doc_templates.html)...

// 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.

如何让字符串进行本地化并嵌入表达式编译?

2 个答案:

答案 0 :(得分: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示例最后会有一个额外的参数。仅当您想要用其他内容替换this属性之一时,才需要这样做。

答案 1 :(得分: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 |插值样本

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

github上的这个帖子真的helped