DEV Community

Cover image for Conditional {i18n}
Isa Ozler
Isa Ozler

Posted on

Conditional {i18n}

For a statistics/analytics dashboard we needed a bit more advanced and customizable localization tool. Due to restriction of external packages, I had to create one :D (Github link / Try it out!)

Basically this is a string interpolation tool which fill the placeholders with data on the fly.

I think what makes this tool nice is that you can have conditional outputs.

Basic example


import i18n from 'dynamic-i18n-io';

// some data
const data = {
  greeting: {
    isMale: true,
    name:   'Joe',
    age:    42
  },
};

// en.js
const format = {
  greeting: {
    // template contains the placeholders text
    template:   `Hello {isMale} {name} {age}`,

    // options is where you put all your values / refs
    // so if
    // greeting.options.name === true ? data.greeting.name
    // will be set to the {name} in the greeting.template literal
    options: {
      isMale: ['Sir', 'Madam'],
      name:   ['{name}', ''],
      age:    ['({age})', '']
    },

    // when condition returns true options[key][0] is set
    // otherwise options[key][1]
    // you can add logic to determine selection with a callback
    conditions: {
      isMale: (props) => props.isMale,
      name:   true,
      age:    (props) => props.isMale || props.age < 20,
    }
  }
};

const { greeting } = i18n(data, format);

// data = { isMale: true, name: 'Joe', age: 42 }
// > 'Hello Sir Joe (42)'

// data = { isMale: false, name: 'Joelle', age: 42 }
// > 'Hello Madam Joelle'

// data = { isMale: false, name: 'Joelle', age: 18 }
// > 'Hello Madam Joelle (18)'

Feel free to fork and improve based on your needs!

Or try it out!

Oldest comments (0)