Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mikermcneil/0af155ed546f3ddf164b4885fb67830c to your computer and use it in GitHub Desktop.
Save mikermcneil/0af155ed546f3ddf164b4885fb67830c to your computer and use it in GitHub Desktop.
Example of dynamically overriding locale in Sails.js
# Example of dynamically overriding locale in Sails.js
For instance, if your app allows users to pick their preferred language, you might create a [policy](http://sailsjs.com/documentation/concepts/Policies) which checks for a custom language in the user's session, and if one exists, sets the appropriate locale for use in subsequent policies, controller actions, and views:
```js
// api/policies/localize.js
module.exports = function(req, res, next) {
// If no user is logged in, continue with the default locale.
if (!req.session.userId) {return next();}
// Load the user from the database
User.findOne(req.session.userId).exec(function(err, user) {
if (err) {return res.serverError(err);}
// Set the locale to the user's preference
req.setLocale(user.languagePreference);
});
};
```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment