Created
February 3, 2017 22:07
-
-
Save mikermcneil/0af155ed546f3ddf164b4885fb67830c to your computer and use it in GitHub Desktop.
Example of dynamically overriding locale in Sails.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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