ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.31k stars 382 forks source link

registerHelper #117

Closed babiz closed 9 years ago

babiz commented 9 years ago

I could not get registerHelper working with this. Could you please show me how to registerHelper. I am trying to use it with i18n module.

ericf commented 9 years ago

It's in the readme: https://github.com/ericf/express-handlebars#helpers You can access handlebars on the ExpressHandlebars instance: https://github.com/ericf/express-handlebars#handlebarsrequirehandlebars

gzurbach commented 9 years ago

@babiz Did you figure out how to create your helper? I tried the following but it doesn't seem to work:

// Configure i18n
i18n.configure({
    locales: ['en', 'fr'],
    defaultLocale: 'en',
    directory: __dirname + '/locales'
});
app.use(i18n.init);

// Configure view engine
var hbs = expressHandlebars.create({
    extname: '.hbs',
    layoutsDir: path.join(__dirname, 'views/email'),
    defaultLayout: 'layout',
    helpers: {
        i18n: function () { return i18n.__.apply(this, arguments); }
    }
});

I'm very close since i18n is being called but it doesn't seem to know what is the current locale. Right now I have everything in English even after forcing the locale to be French.

gzurbach commented 9 years ago

Hmm. I got it working by using req which contains the locale of the user. I'd be happy to know if there is a better way.

// Configure view engine
var hbs = expressHandlebars.create({
    extname: '.hbs',
    layoutsDir: path.join(__dirname, 'views/email'),
    defaultLayout: 'layout'
});

// Add i18n helper to handlebars
app.use(function (req, res, next) {
    hbs.handlebars.registerHelper('i18n', function () {
        return i18n.__.apply(req, arguments);
    });
    next();
});

Also, I think it'd be nice to add the solution to the documentation. Or even better, add i18n support into this library.

babiz commented 9 years ago

Yes Gzurbach. I tried to use the registerhelper but it did not work for me. Not sure what I was doing wrong so I did the following and it is working fine.

   var hbs = exphbs.create({
        defaultLayout: 'main',
        extname: '.html',
        layoutsDir: path.resolve('./app/admin/views/layouts'), 
        helpers: {
            __: function (textToBeTranslated) {
                return i18n.__(textToBeTranslated);
            },
        }
    });
JuoCode commented 9 years ago

Reference express-hbs 's helper

  args = Array::slice.call(arguments)
  options = args.pop()
  i18n.__.apply options.data.root, args