i18n-node icon indicating copy to clipboard operation
i18n-node copied to clipboard

Make use of the translation methods in browser

Open LucianoGanga opened this issue 9 years ago • 5 comments

Hi!

I'm using i18n-node in my KoaJS server. It works great! But sometimes I need to make some translations browser side (for example, when a toast is generated from a javascript function, and including some data that the user just filled in some field).

As I don't want to hit the server every time I need a translation, what I managed to do was adding a copy of the translations in local storage, and refreshing it only when it's necessary (ie., a text in en.js was modified).

To handle the translations in the browser now I'm using Polyglot, that allows me to load an object with the translations and call a simple .t()method to translate something... But the thing is that I want to use all the good things in i18n-node, like Plurals translations, message format, etc.

Is there a way to make i18n work in browser by loading the translations from a JS object instead of from a file?

Thanks! Luciano

LucianoGanga avatar Jul 13 '16 18:07 LucianoGanga

browser support is not yet available directly. The only working example I am aware of is https://docs.omniref.com/js/npm/i18n-node-angular/0.2.0

Adding full browser support will need to wait until 1.0.0 as I want to refactor for supporting webpack, browserify & Co...

mashpie avatar Jul 19 '16 15:07 mashpie

In the meantime, a note on how we achieved this is to create an endpoint on the server which will serve up the JSON file of the user's current locale.

router.get('/i18n.js', (req, res) => {
  var catalog = i18n.getCatalog(req)
  res.send('window.i18nCatalog = ' + JSON.stringify(catalog))
})

You can then create a fairly simple function for retrieving values from your locale object.

emmerich avatar Aug 03 '16 09:08 emmerich

Thanks! I did something like that, but sending the translations in the response object, and then saving them in Local Storage. By doing that, I avoid requesting those translations when they haven't change. I store a cookie with a timestamp to check when I need to download them again.

LucianoGanga avatar Aug 04 '16 14:08 LucianoGanga

I just stumbled upon this https://github.com/gammasoft/browser-i18n

thenitai avatar Dec 15 '16 10:12 thenitai

You shouldn't call the server to get phrases, this is unnecessary.

What I do is something like this:

<script>
    var lang = {
        'phrase1': "{{ __('phrase1') }}",
        'phrase2': "{{ __('phrase2') }}"
    };
</script>
<script src="js/all.bundle.js"></script>

Then, in my JavaScript file all.bundle.js, I use lang.phrase1, lang.phrase2 etc.

Milad avatar Oct 14 '17 00:10 Milad