Sailsjs change localization
Asked Answered
H

2

8

I've been using Sails.js for quite some time and was wondering if there is a way to manually change the localization from the controllers depending on the url.

Example: http://example.com/en will return the English version and http://example.com/de will return the German one.

Thanks for your help!!

Handoff answered 22/1, 2014 at 21:53 Comment(0)
B
11

You can always change the locale in a controller action by using req.setLocale() or by setting the value of req.locale. You can also handle this more globally by using a policy:

// config/routes.js

module.export.routes = {

  '/:lang/': 'MyController.index',
  '/:lang/help': 'MyController.help',
  '/:lang/contact': 'MyController.contact',
  ...etc...

}

// config/policies.js

module.exports.policies = {

   '*' : 'localize'

}

// api/policies/localize.js

module.exports = function(req, res, next) {

   req.locale=req.param('lang');
   next();

};
Bureaucracy answered 23/1, 2014 at 18:9 Comment(4)
No way of setting the locale without a controller? sails.setLocale for example? I'm using cronjob hook, and I cant access the req that way.Ultimogeniture
@StasArshanski not really sure what you mean -- can you open a new question with more details of what you're trying to do?Bureaucracy
yea here: #45533081Ultimogeniture
How about the API requests? For example: We send a post request with body data: { lang: 'fr' } Or set something on request headers. Then we can return text with French language?Exactitude
I
1

Update 2020 to @sgress454's answer

// api/policies/localize.js`

module.exports = function(req, res, next) {
  // This worked for testing
  // You can use req.param('lang') instead of 'in'
  req.setLocale('in');
  next();

};
Iman answered 19/5, 2020 at 2:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.