Code Monkey home page Code Monkey logo

meteor-internationalization's Introduction

support support

Reactive i18n and l10n isomorphic driver

Object based, fast, lightweight (334 lines with comments) and reactive internationalization isomorphic driver for Meteor with support of placeholders, and user's locale auto-detection.

Not tied to Blaze, can be used with Vue.js, React.js or any other JS solution.

Install:

meteor add ostrio:i18n

Import:

import I18N from 'meteor/ostrio:i18n';

Object-based structure

/* Isomorphic (Both Server and Client) */
const i18nConfig = {
  settings: { //--> Config object
    defaultLocale: "en",
    ru: {
      code: "ru",
      isoCode: "ru-RU",
      name: "Русский"
    },
    en: {
      code: "en",
      isoCode: "en-US",
      name: "English"
    }
  },
  ru:{ //--> Localization with key of country two-letter code
    property: "value",
    property2: {
      nestedProp: "value"
    },
    dynamicProperty(){
      return `<a href="/${this.currentLocale.get()}/info">info</a>`;
    }
  },
  en:{ //--> Localization with key of country two-letter code
    property: "value",
    property2: {
      nestedProp: "value"
    },
    dynamicProperty(){
      return `<a href="/${this.currentLocale.get()}/info">info</a>`;
    }
  }
  ...
};

import I18N from 'meteor/ostrio:i18n';
const i18n = new I18N({i18n: i18nConfig});

Initialization

import I18N from 'meteor/ostrio:i18n';
const i18n = new I18N(config);
  • config.i18n {Object} - Internalization object
  • config.returnKey {Boolean} - Return key if l10n value not found, default: true
  • config.helperName {String} - Template helper name, default: i18n
  • config.helperSettingsName {String} - Settings helper name, default: i18nSettings

API

get([locale,] key, [replacements...])

  • locale {String} - [Optional] Two-letter locale string, used to force locale, if not set current locale is used
  • key {String} - l10n key like: object.path.to.key
  • replacements.. {String|[String]|Object} - [Optional] Replacements for placeholders in l10n string
i18n.get('object.path.to.key'); // Current locale, no replacements

i18n.get(locale, param); // Force locale, no replacements
i18n.get('en', 'object.path.to.key');

i18n.get(param, replacements); // Current locale, with replacements
i18n.get('object.path.to.key', 'Michael'); // Hello {{username}} -> Hello Michael

i18n.get(locale, param, replacements); // Force locale, with replacements
i18n.get('en', 'object.path.to.key', 'John Doe'); // Hello {{username}} -> Hello John Doe

has([locale,] key)

Determine whenever key is exists in configuration file(s).

  • locale {String} - [Optional] Two-letter locale string, used to force locale, if not set current locale is used
  • key {String} - l10n key like: object.path.to.key
i18n.has('object.path.to.key'); // Current locale
i18n.has(locale, param); // Force locale
i18n.has('ca', 'object.path.to.key'); //false
i18n.has('en', 'object.path.to.key'); //true

setLocale(locale)

  • locale {String} - Two-letter locale code
i18n.setLocale(locale);

addl10n(l10n)

  • l10n {Object} - Object with language set
i18n.addl10n({
  en: { // <- Object's root is the language two-letter code
    newKey: "New Value"
  }
});

Get current localization at any environment

i18n.currentLocale.get(); // Reactive on Client

Get current default locale

i18n.defaultLocale;

Get configuration object

i18n.langugeSet();
/* Returns:
{
  current: 'en', // Current locale
  locales: ['ru', en], // List of locales
  // All locales
  all: [{
    code: "ru",
    isoCode: "ru-RU",
    name: "Русский",
    path: "i18n/ru/"
  },{
    code: "en",
    isoCode: "en-US",
    name: "English",
    path: "i18n/en/"
  }],
  // All locales except current
  other: [{
    code: "ru",
    isoCode: "ru-RU",
    name: "Русский",
    path: "i18n/ru/"
  }],
}
*/

Get specific key from configuration object

  • key {String} - One of the keys: current, all, other, locales, currentISO, currentName, currentPath
i18n.getSetting('current'); // en

Blaze specific usage

Usage in Blaze templating

Client's browser locale

i18n.userLocale; // en-US

Template helpers

Template helpers requires templating package to be installed. i18n helper - accepts locale, key and replacements

<p>{{i18n 'sample.hello'}}</p>
<p>{{{i18n 'sample.html'}}}</p>
<p>{{i18n 'sample.fullName'}}</p>
<p>{{i18n 'sample.fullName' 'Michael' 'A.' 'Macht'}}</p>
<p>{{i18n 'en' 'sample.fullName' 'Michael' 'A.' 'Macht'}}</p>
<p>{{i18n 'de' 'sample.fullName' first='Michael' middle='A.' last='Macht'}}</p>
<p>{{i18n 'sample.fullName' first='Michael' middle='A.' last='Macht'}}</p>
<p>{{i18n 'sample.fullName' first='Michael' middle='A.' third='Macht'}}</p>

Change name of the helper via config object: config.helperName

i18nSettings - accepts configuration object key, one of current, all, other, locales

{{#each i18nSettings 'all'}}
  ...
{{/each}}

Change name of the helper via config object: config.helperSettingsName

Template language switcher example

<template name="langSwitch">
  {{#each i18nSettings 'all'}}
    {{#if compare code '==' currentLocale}}
      <span title="Current language">{{name}}</span>&nbsp;
    {{else}}
      <a href="#" data-switch-language="{{code}}">{{name}}</a>&nbsp;
    {{/if}}
  {{/each}}
</template>
Template.langSwitch.helpers({
  currentLocale(){
    return i18n.currentLocale.get()
  }
});

Template.langSwitch.events({
  'click [data-switch-language]'(e) {
    e.preventDefault();
    i18n.setLocale(e.currentTarget.dataset.switchLanguage);
    return false;
  }
});

Template helpers compare, ==, Session and many more comes from: ostrio:templatehelpers package.

Support this project:

meteor-internationalization's People

Contributors

dr-dimitru avatar jankapunkt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

meteor-internationalization's Issues

Passing number to options will not replace the placeholder

Reproduction:

  • define i18n.json with a simple replacer pattern:
{
  "max": "You reached {{max}} %"
}

Then pass a number value to it:

const max = 75
i18n.get('max', { max }) // returns You reached {{max}} %

If the value is a string, it's all fine:

const max = '75'
i18n.get('max', { max }) // returns You reached 75 %

Meteor Example

Is there a complete Meteor/Blaze and Meteor/React example I can reference?

Thanks!

Fiber

@RavisMsk
if I comments all lines which runs (initiate) i18n I still get errors.
By removing Fiber = Npm.require "fibers" - every gets fine, until you run i18n and didn't get Fiber is not defined error

I've pushed non error code, with commented lines
Any idea around this?

how to SWITCHER language UI?

I try add this to my template:

// home.html
{{> i18nSwitcher}}
---------------------------
<template name="i18nSwitcher">
  <ul class="">
    {{#each Session 'i18nConfig'}}
      {{> i18nList}}
    {{/each}}
  </ul>
</template>

<template name="i18nList">
{{#if this.value.code}}
  {{#if compare this.value.code '!==' this.currentLocale}}
    <li>
      <a href="#" onclick="i18n.setLocale('{{this.value.code}}'); return false;">{{this.value.name}}</a>
    </li>
  {{/if}}
{{/if}}
</template>

but don't show any thing.

Can all properties be stored in a separate json or yml file per language?

Hi thanks for sharing this. Quick question: Can all properties be stored in a separate json or yml file per language?

The readme file seems to indicate a path to a file for each language/locale, but I can't find a specific example... not sure if the file should be JSON or YML or if the name matters.

path: "i18n/ru/"

Make Template helpers optional

We use a custom Template helper and would like to omit the internal one, for example by passing helperName: null and helperSettingsName: null. If null is passed then there would be no helper created.

Example would be:

      if (typeof Template !== 'undefined' && Template !== null) {
        if (this.helperName !== null) {
          /**
           * @summary Main `i18n` template helper
           */
          Template.registerHelper(this.helperName, function () {
            return self.get.apply(self, arguments);
          });
        }

        if (this.helperSettingsName !== null) {
          /**
           * @summary Settings `i18n` template helper, might be used to build language switcher (see demo folder).
           */
          Template.registerHelper(this.helperSettingsName, function () {
            return self.getSetting.apply(self, arguments);
          });
        }
      }

what do you think?

please change file structure in doc (duplicate en)?

β”œβ”€β”€ en/ //--> Localization folder with name of country two-letter code
    |   β”œβ”€β”€ file.json
    |   └── subFolder/ 
    |       └── anotherFile.json
    |
    β”œβ”€β”€ en/ //--> Localization folder with name of country two-letter code
    |   β”œβ”€β”€ file.json
    |   └── subFolder/ 
    |       └── anotherFile.json
    |

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.