Last active
March 19, 2022 18:36
-
-
Save antsanchez/6f08c0bbe209504bd3456ca45d2c56a8 to your computer and use it in GitHub Desktop.
Localization Express.js: Language in URL
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
const express = require('express'); | |
var app = express(); | |
var hbs = require('hbs'); | |
var i18n = require("i18n"); | |
var _ = require('lodash'); | |
app.set('view engine', 'hbs'); | |
// Available languages | |
let locales = ['es', 'de', 'en', 'fr', 'it']; | |
// Set up i18n | |
i18n.configure({ | |
locales: locales, // locales disponibles | |
defaultLocale: 'en', // local por defecto | |
directory: __dirname + '/locales' // directorio donse se guardan las traducciones en formato .json | |
}); | |
// Middleware to detect the locale on url | |
app.use(function(req,res,next){ | |
// Helper to use i18n inside HBS | |
res.locals.__ = res.__ = function() { | |
return i18n.__.apply(req, arguments); | |
}; | |
// Look for the locale on the first tram of the url | |
// example: www.example.com/local/path | |
var path = _.split(req.path, "/", 2) | |
locales.forEach( (locale) => { | |
if(path[1] == locale){ | |
// if detected, use it | |
i18n.setLocale(req, locale); | |
} | |
}); | |
next(); | |
}) | |
// Crate a route for every locale | |
locales.forEach( (locale) => { | |
app.get('/' + locale, function(req, res) { | |
res.send(locale); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment