jeresig / i18n-node-2

Lightweight simple translation module for node.js / express.js with dynamic json storage. Uses common __('...') syntax in app and templates.
MIT License
507 stars 79 forks source link

Auto-detect supported locales from locales directory? #22

Closed aseemk closed 9 years ago

aseemk commented 10 years ago

It would be great if I didn't have to specify the locales manually, if instead it could just be derived automatically by seeing which extension (e.g. .js) files were in directory (e.g. ./locales).

That way, you wouldn't need to maintain the list of locales in the configuration separately from the files you've had translated.

Would you be open to that? I might be able to put together a pull req if so. Thanks again for the great lib!

digitalsweetspot commented 10 years ago

couldn't you just do something like:


// set requires
var express = require('express')
  , I18n = require('i18n-2')
  , fs = require('fs')
;
// load all locales
var localesPath = './app/locales';
var locales = [];
fs.readdirSync(localesPath).forEach(function (file) {
  if (file.indexOf('.json') >= 0) {
    locales.push(file.replace('.json',''));
  }
});
module.exports = function(app) {
  app.configure(function () {
    I18n.expressBind(app, {
        locales: locales
      , cookieName: 'locale'
      , directory: localesPath
      , extension: '.json'
    });
    app.use(express.compress());
    app.use(express.static(envConf.root + '/public'));
    app.set('port', envConf.port);
    app.set('views', envConf.root + '/app/views');
    app.set('view engine', 'ejs');
    app.use(express.favicon(envConf.root + '/public/images/favicon.png'));
    app.use(express.logger(':method :url :status'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    // add support for cookies
    app.use(express.cookieParser());
    app.use(express.session({ secret: 's0meCrazySecr3tC0d3 }));
    // This is how you'd set a locale from req.cookies.
    // Don't forget to set the cookie either on the client or in your Express app.
    app.use(function(req, res, next) {
      req.i18n.setLocaleFromCookie();
      next();
    });
    // add support for routes
    app.use(app.router);
  });
};
gjuchault commented 9 years ago

Closed (the comment answers the issue)