simple-i18n-example
simple-i18n-example copied to clipboard
Support for interpolation
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.
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!
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.