Skip to content

Instantly share code, notes, and snippets.

@JedWatson
Created February 24, 2014 16:00
Show Gist options
  • Star 40 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save JedWatson/9191081 to your computer and use it in GitHub Desktop.
Save JedWatson/9191081 to your computer and use it in GitHub Desktop.
Example of how to integrate node-i18n with a KeystoneJS app (using yo keystone generated site as a basis) - see https://github.com/mashpie/i18n-node for more docs.
// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require('dotenv')().load();
// Require keystone and i18n
var keystone = require('keystone'),
i18n= require('i18n');
// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.
keystone.init({
'name': 'Your Site',
'brand': 'Your Site',
'less': 'public',
'static': 'public',
'favicon': 'public/favicon.ico',
'views': 'templates/views',
'view engine': 'jade',
'auto update': true,
'session': true,
'auth': true,
'user model': 'User',
'cookie secret': 'your secret'
});
// Load your project's Models
keystone.import('models');
// Setup common locals for your templates. The following are required for the
// bundled templates and layouts. Any runtime locals (that should be set uniquely
// for each request) should be added to ./routes/middleware.js
keystone.set('locals', {
_: require('underscore'),
env: keystone.get('env'),
utils: keystone.utils,
editable: keystone.content.editable
});
// Configure i18n
i18n.configure({
locales:['en', 'de'],
directory: __dirname + '/locales'
});
// Load your project's Routes
keystone.set('routes', require('./routes'));
// Configure the navigation bar in Keystone's Admin UI
keystone.set('nav', {
'posts': ['posts', 'post-categories'],
'galleries': 'galleries',
'enquiries': 'enquiries',
'users': 'users'
});
// Start Keystone to connect to your database and initialise the web server
keystone.start();
var _ = require('underscore'),
keystone = require('keystone'),
i18n = require("i18n"),
middleware = require('./middleware'),
importRoutes = keystone.importer(__dirname);
// Add-in i18n support
keystone.pre('routes', i18n.init);
// Common Middleware
keystone.pre('routes', middleware.initLocals);
keystone.pre('render', middleware.flashMessages);
// Import Route Controllers
var routes = {
views: importRoutes('./views')
};
// Setup Route Bindings
exports = module.exports = function(app) {
// Views
app.get('/', routes.views.index);
app.get('/blog/:category?', routes.views.blog);
app.get('/blog/post/:post', routes.views.post);
app.get('/gallery', routes.views.gallery);
app.all('/contact', routes.views.contact);
}
@hrsalazar
Copy link

Thanks mate, really easy to integrate

@scottbaggett
Copy link

Thanks!

@arruah
Copy link

arruah commented Dec 7, 2014

@JedWatson @changetip 100 satoshi

@BANG88
Copy link

BANG88 commented Dec 21, 2014

Its does't work for me,I use the default view engine. 🆘

@piermariacosina
Copy link

How you get the routing for the locales? like 0.0.0.0:3000/en/?

@arthurtalkgoal
Copy link

Hi, Anyone getting it works in the jade template?

I set up every thing above without error, but in jade,
I got _Cannot read property 'organisation.other' of undefined_ :

organisations.jade

= __("organisation.other")

en.json

{
    "app": {
        "name": "CatchTop Platform"
    },
    "creator": {
        "firstname": "Arthur",
        "lastname": "CHAN"
    },
    "organisation": {
        "one": "Organisation",
        "other": "Organisations test"
    },
}

Seems that it cannot find __ function in _.jade_

@Goye
Copy link

Goye commented Jun 10, 2015

@piermariacosina for the language using the routing you can add on your index.js
app.get('/:lang', routes.views.index);
and in the middleware before the pre routes (in the pre render), you can get your language variable and change it using req.setLocale(req.params.lang);

@pedro-couto
Copy link

@arthurtalkgoal did you try to use in jade the following: #{__('organisation.other')} ? for me its working.

@maxkoryukov
Copy link

Handlebars context issue

I had a problem with helpers-context: in the inner scope (for example, inside of helpers each, or with) __ is inaccessible:

{{!-- This works --}}
{{__ "Translatable text"}}

{{!-- This cause an error "Missing helper: '__'" --}}
{{#each data.posts}}
    {{__ "Translatable text"}}
{{/each}}

As a consequence - it is not possible to use i18n for inner markup...

Here is a dirty solution: I have overloaded the res.render, to provide implicit passing of local helpers (this means, that this each request will have its own helpers - it is important) to the render method, and next, to handlebars engine (as described here: https://github.com/ericf/express-handlebars#helpers ).

// somewhere :
var _ = require('lodash');
// ....
// some code...
// ....

app.use(function(req, res, next){

    let render_old = res.render;
    res.render = function render(vn, opt, cb){
        if (_.isNil(opt)){
            opt = { helpers: { __ : res.locals.__ } };
        } else {
            _.set(opt, 'helpers.__', res.locals.__);
        }

        arguments[1] = opt;
        return render_old.apply(this, arguments);
    }

    return next();
}

Add this code to the routes - index.js after keystone.pre('routes', i18n.init); , line 9 in the example above.

@maufarinelli
Copy link

I didn't understand how to setup the default language. Where is it?
is it implicit the first language of the array?

Also, using Jade, #{__('title-site')} , when I load the website, i see title-site.

Finally, I just realized that, each time I a reloading the page, my json has been updated??? Now I have

{
  "title-site": "title-site"
}

@ricardopereira
Copy link

This will affect the admin as well?

@ghuroo
Copy link

ghuroo commented Jan 26, 2017

the correct way to access i18n data with Pug.js (I suppose Jade too) is:

index.js: i18n.configure({ locales: ['en', 'de'], directory: __dirname + '/locales', autoReload: true, syncFiles: true, objectNotation: true, });

routes/index.js:
keystone.pre('routes', i18n.init);

en.json:
{ "hello": "hello", "navigation": { "about": "about our awesome company" } }

template.pug (with objectNotation):
span= __('navigation.about') or span #{ __('navigation.about') }

template.pug (without objectNotation):
span= __('navigation').about or span #{ __('navigation').about }

@arikanmstf
Copy link

Hello , how to implement i18n for admin panel ?

@talvasconcelos
Copy link

Hi guys, i have this working. I now need a way to change the locale from the DOM. i want the user to have the ability to change to language he seems better.

Also, if i enable cookie, how do i save the user's language choice to the cookie, so that he doesn't need to change it every time?
thanks,
Tiago

Copy link

ghost commented Jun 13, 2017

Dear all
I almost port i18n successfully. However, i am having final problem that how i can use i18n for text in flash-messages (mixins folder).
Hope you can help me

Thank you so much for your help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment