Peter Van de Put
Peter Van de Put

Reputation: 938

how to create language selector in node

I am relatively new to node.js and am using node, express and mongoose. I have implemented i18n module and configured Now I need a drop down with the supported languages with flag icons and on click want to call the setLocale() but don't know how to do this All ideas are welcome.

Also in not all the jade templates the __('hello') translation is picked up e.g

.dropdown
    button.btn.dropdown-toggle(type='button', id='dropdown1',data-toggle='dropdown')
        img(src='/img/navbar-list.png', alt='Cloud iBeacon')
    ul.dropdown-menu(role='menu',aria-labelledby="dropdownMenu1")
        li(role='presentation')
            a(role='menuitem',href="/") __('home')

Doesn't work

Upvotes: 0

Views: 2735

Answers (1)

damphat
damphat

Reputation: 18956

That depends on how you config i18n, if you use a cookie named 'locale' to store locale:

// minimal config
i18n.configure({
  locales: ['en', 'fr'],
  cookie: 'locale',
  directory: __dirname + '/locales'
});

// express.cookieParser then i18n.init

  app.use(express.cookieParser());
  app.use(i18n.init);

then you can set locale via cookie, set this route to your app:

// set a cookie to requested locale
app.get('setlocale/:locale', function (req, res) {
  res.cookie('locale', req.params.locale);
  res.redirect('back');
});

then create menu with 2 items en, fr. (as your example, bootstrap?)

.dropdown
    button.btn.dropdown-toggle(type="button" data-toggle="dropdown") Dropdown
    ul.dropdown-menu
        li: a(href="/setlocale/en") en
        li: a(href="/setlocale/fr") fr

example here:

https://github.com/mashpie/i18n-node/blob/master/examples/express-jade/express-jade.js

Upvotes: 4

Related Questions