Skip to content

Instantly share code, notes, and snippets.

@mosson
Created January 21, 2016 11:17
Show Gist options
  • Save mosson/ffc9e861671078278979 to your computer and use it in GitHub Desktop.
Save mosson/ffc9e861671078278979 to your computer and use it in GitHub Desktop.
'use strict';
import _ from 'lodash';
import Request from 'superagent';
import Promise from 'bluebird';
class I18n {
load(path) {
return new Promise((f, r) => {
Request
.get(path)
.end((err, res) => {
if (err) return r(err);
this.dictionary = _.extend(this.dictionary || {}, JSON.parse(res.text));
f();
});
});
}
translate(key, params) {
if (!this.dictionary) return '';
params = params || {};
let string = _.reduce(key.split('.'), (result, token) => {
return (result || this.dictionary)[token];
}, null);
return (string || '')
.replace(/\%\{(\w+?)\}/g, (__, prop) => {
return (params[prop] || '');
});
}
}
const instance = new I18n();
const t = instance.translate.bind(instance);
export { t };
export default instance;
@mosson
Copy link
Author

mosson commented Jan 21, 2016

class App extends Component {
  componentDidMount() {
    this._setupLocale({locale: global.locale || 'ja'});
  }

  _setupLocale(locale) {
    I18n
      .load(pathToRegexp.compile(Constant.LOCALE_ENDPOINT)(locale))
      .then(I18n.load.bind(I18n, pathToRegexp.compile(Constant.COMMON_LOCALE_ENDPOINT)(locale)))
      .then(this.forceUpdate.bind(this))
      .catch((err) => {
        Action.MessageAPI.error.call(Action, null, err);
      });
  }
}

@mosson
Copy link
Author

mosson commented Jan 21, 2016

{
  "surveys": {
    "List": {
      "body_html": "新しいアンケートを<br/>作成しましょう"
    },
    "Aside": {
      "surveys_list": "アンケート一覧",
      "share": "招待・共有設定",
      "plan": "プラン設定",
      "account": "アカウント設定",
      "template": "テンプレートギャラリー",
      "help": "ヘルプ・サポート",
      "legacy": "旧バージョンにする",
      "notification": "お知らせ",
      "read_more": "詳しく見る",
      "execute": "実行する",
      "External": {
        "template": "テンプレートギャラリー",
        "help": "ヘルプ・サポート",
        "legacy": "旧バージョンにする"
      }

@mosson
Copy link
Author

mosson commented Jan 21, 2016

import { t } from 'services/I18n';

//...

<li className="SurveyComponent__ControlItem">
  <button type="button"
                className="SurveyComponent__ControlItemConfig"
                cs-tooltip="true"
                title={t('surveys.SurveyComponent.config')}
                onClick={this._editHdl.bind(this)}>
    <span>{i.Config}</span>
  </button>
</li>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment