Tuesday 23 May 2017

can not detect current language (i18next.language) from handlebar helper?

I am using following packages for multi-languages solutions.

var i18next = require('i18next');

var i18nFsBackend = require('i18next-node-fs-backend');

var i18nMiddleware = require('i18next-express-middleware');

Since I am using handlebar as my nodejs template engine, that's I can not use i18next t('key') directly in the HTML. so I created a handlebar helper like following

     ```javascript
     var i18next = require('i18next');
     handlebars.registerHelper('t', function(i18n_key) {
         console.log(i18next.language)// always undefined, so i18next.t(i18n_key) always return default translation.   
         var result = i18next.t(i18n_key);
         return new handlebars.SafeString(result);
     });
     ```

However, the problem was the function is unable to detect language changed

My Workaround

app.js

    ```javascript
    var i18nextInitCallback = function(error, t){

        handlebars.registerHelper('t', function(i18n_key) {

            if(app.locals.language !== i18next.language){
                i18next.changeLanguage(app.locals.language);
            }

            var result = i18next.t(i18n_key);
            return new handlebars.SafeString(result);
        });
    };
    ```

route

    ```javascript
    router.use(function(req, res, next){
        res.locals.lng = req.language;
        res.app.locals.language = req.language;
        next();
    });

    ```

as you can see that on Route I assign res.app.locals.language = req.language; and then in the handlebar helper function, I use app.locals.language to get the current language and use i18next.changeLanguage() to change the language.

and it worked.

I would like to know if I am doing it right or not? or if there is a better solution



via Kongfupanda

No comments:

Post a Comment