Q
Q
quex2014-05-03 00:24:47
Node.js
quex, 2014-05-03 00:24:47

What is the best way to organize multilingualism in express?

What is available:
- a middleware in express, which determines the language on each request and writes it to the req._lang variable, after which req is passed further down the chain
- the Translate class with the #setLocale(lang) method (sets the default translation language to lang) and #_(lang, phrase, args) method (translates phrase string with args arguments into lang language (if null - default))
- templating engine
Obvious option

var t = new Translate({..});
var app = express();

app.get('/url', function(req, res){
    var nick, name;
    ...
    t.setLocale(req._lang);
    res.render('template.html', {
        title: t._('Hello, %s', nick),
        description: t._('This is a long description, my dear %s, ...', name)
    });
});

// template.html
<h1><%= title %></h1>
<div><%= description %></div>

looks extremely unkosher, I want to have something like
app.get('/url', function(req, res){
    var nick, name;
    ...
    res.render('template.html', {
        nick: nick,
        name: name
    });
});

// template.html
<h1><% _('Hello, %s', nick) %></h1>
<div><% _('This is a long description, my dear %s, ...', name) %></div>

those. we give the template only raw data, and it chooses the translation and formats it.
an example of how I imagine it
var t = new Translate({..});
var app = express();

// мидлвар
app.use(function(req, res, next){
     req._ = function(phrase, args){
          return t._(req._lang, phrase, args);
     }
});

those. we have the req#_() method, a complete analog of the native #_(), except that it automatically substitutes the language and does not change the global scope of the t object (via #setLocale()),
only how to use it inside the template when rendering now? how do you actually implement this? Are there better implementations?
thank.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Eugene Obrezkov, 2014-05-03
@quex

Look at Sails , they have just such a contraption implemented.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question