jeresig / i18n-node-2

Lightweight simple translation module for node.js / express.js with dynamic json storage. Uses common __('...') syntax in app and templates.
MIT License
507 stars 79 forks source link

Using i18n in js files #115

Closed guiguitcho closed 6 years ago

guiguitcho commented 6 years ago

Hello I am using i18n in express with pug templating and it works as expected as long as i18n__ expressions are in pug files. However when I try to use it in js files, included inside the pug files, it doesn't work: i get Uncaught ReferenceError: i18n is not defined I guess it is because in that case, javascript is only evaluated client side which is aware of i18n library.

However is there any way to be able to use i18n in js files ?

Many thanks in advance !

gjuchault commented 6 years ago

Well there is no point using i18n on client side: this would be a lost of bandwith, processing time, etc. There is no simple way to template JS files. One solution would be to generate json files that are shipped with webpack or stuff like that, so that you can get maximum performances :). Anyway, this has nothing to do with i18n-node-2 and you might get more answers from StackOverflow or other alternatives. Good luck tho

guiguitcho commented 6 years ago

Thank you very much I will follow your advice !

guiguitcho commented 6 years ago

FYI I have found a simple workaround, not perfect but which fits my needs: I put all the needed translation in an object server-side

router.get('/', function(req, res, next) {
    var tr_Object = {
        "temperature": req.i18n.__('temperature')
    }
    res.render('test', {
        title: req.i18n.__("test"),
        tr_data: JSON.stringify(tr_Object)
     });
});

In the test.pug file I can access the object simply using

script(type='text/javascript').
    var transText =  !{tr_data}

and use the object in my js files client side.

Hope that will help !