simple-i18n-example icon indicating copy to clipboard operation
simple-i18n-example copied to clipboard

Support for interpolation

Open jeremycod opened this issue 4 years ago • 2 comments

Hi,

I've applied this approach in my project and only now I've realized it doesn't support interpolation. Any suggestion how to solve that without having to completely apply different library? I'm using serverless approach, so it was a little bit tricky to make multilanguage approach work.

jeremycod avatar Jul 31 '20 17:07 jeremycod

I don't use it so I've never implemented. This was never intended as a full-featured library, but more like an idea to get people started in creating their own implementation. All I can suggest is have a look at how other libraries do interpolation and see if you can implement your own version - I don't expect this to be particularly difficult. Good luck!

fwojciec avatar Jul 31 '20 19:07 fwojciec

Basic idea is pretty straightforward

You pass translated string (stored accordingly) and variables to be plugged to helper function.

const interpolation = (str, ...val) => {
  let i = 0;
  return str ? str.replace(/({\w+})/g, () => val[i++]) : str;
};

and if your translation has to incorporate any variable simply store it like so

...
"someKey": "{this} will be interpolated, and also {this one}"; // strings in brackets are only descriptive, they do not effect anything
...

E.g.

interpolation(translationStrings[someKey], 'one', 'two') // => One will be interpolated, and also two

Brackets {} are arbitrary, you can pick whatever symbol you want, the one which suits to your needs and fits translations. Just remember to update regexp in interpolation helper function.

You can define helper function in your shared translation logic, e.g for this project we have context object.

ogostos avatar Aug 10 '20 07:08 ogostos