Simple library to localize your app
<%- t("menu.home") %>
Install node.js library:
npm install localize-simple
var localize = require('localize-simple');
//syntax
app.use(localize({ router: router, path: locales_path, default: default_locale }));
//example
app.use(localize({
router: app,
path: path.join(__dirname, 'locales'),
default: "es"
}));
-
router
: an express instance or another router likerouter.get(url, callback)
. -
path
: path to your locales folder which must to contains at least a .js file with name of default_locale, e.g.: en.js -
default
: default value for locale that will be load if there isn't no locale set at session. If not passed"en"
will be taken instead
We need to have the same structure between locale files, like this:
//en.js
module.exports = {
menu: {
home: "Home"
}
};
//es.js
module.exports = {
menu: {
home: "Inicio"
}
};
So in views you can do:
<%- t("menu.home") %>
And that's it!
To change locale localize-simple declares the get route '/locale/:lang/*'
, :lang is the locale to change, e.g.: en, es or any locale that you've declared. The wildcard *
is the return_url to go after changing the locale.
If we want to have a link to change locales you can have:
<a href="/locale/es/about">ES</a>
<!-- and/or -->
<a href="/locale/en/about">EN</a>
Clicking the one of the links above localize-simple will change the locale and redirect to /about.
If you have a whole partial whose content must change depending on the locale, you also have access to variable called lang whose value is the current locale, e.g:
<% if (lang === "en"){ %>
<%- partial("profile_en") %>
<% } %>
<% if (lang === "es"){ %>
<%- partial("profile_es") %>
<% } %>
<!-- or just -->
<%- partial("profile_"+lang) %>
If you want to have some variable in your translation you can do this:
//en.js
module.exports = {
menu: {
home: "Home",
download: "Download our {version} version"
}
};
//es.js
module.exports = {
menu: {
home: "Inicio",
download: "Descarga nuestra versión {version}"
}
};
<%- t("menu.download", {version: "2.5"}) %>
And you'll get:
for en:
Download our 2.5 version
for es:
Descarga nuestra versión 2.5
If you have a structure like this:
//en.js
module.exports = {
menu: {
home: "Home",
download: "Download our {version} version"
}
};
But you want to get the locale text for menu:
<%- t("menu") %>
Right now you'll get the message: translation missing for: [locale].menu, but you can't define another menu key at the same path, you can do this:
//en.js
module.exports = {
menu: {
default: "Menu",
home: "Home",
download: "Download our {version} version"
}
};
And now you'll get the right text you want.
For support or contact you can write to samuelluis@outlook.com. If you found a bug or have any suggestions, please post an issue.
Thanks for collaborating!