Sanjay Zalke
Sanjay Zalke

Reputation: 1371

SailsJs Handlebar helper functions does not work

I am using Handlebars as templating engine for Sailsjs. Basic templating is working fine but I can't find out the way to use Handlebars helper function or even built in functions are not available.

I have managed to solve the issue with partials using following article. https://github.com/balderdashy/sails/issues/2414

I have also registered the helpers.js in config folder but I can't call any custom, built in blocks or iteration helper function.

Any pointers to solve the issue of helpers will be helpful. Sailsjs verion - 0.11.4 Handlebars version - 4.0.5

I have registered the helper function in above file like this:

Handlebars.registerHelper('help', function() {
    return "help22";
});

And I am calling the same in my template:

{{{help}}}

Any idea why it is not rendering?

Upvotes: 0

Views: 710

Answers (2)

Jan Madeyski
Jan Madeyski

Reputation: 359

Above solution didn't work for me - I got error "Handlebars is not defined" because I didn't check this link- https://github.com/balderdashy/sails/issues/2414

I have had to add Handlebars = require('handlebars'); in /config/helpers.js

Putting all together:

Edit file /config/views.js

module.exports.views = {
      engine: 'handlebars',
      extension: 'html',      // optional
      layout: 'layouts/main', // optional, will load /views/layouts/main.html
      partials: 'partials',   // optional, will load partials from /views/partials/
      helpers: require('./helpers') // <-- this is it
};

Create file /config/helpers.js

Handlebars = require('handlebars');
module.exports = Handlebars.helpers;

Handlebars.registerHelper('stringify', function(obj) {
    var json = {}, prop, tmp;
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            try {
                tmp = JSON.stringify(obj[prop]);
                json[prop] = obj[prop];
            } catch (e) {
                json[prop] = '[CAN NOT stringify]';
            }
        } 
    }
    return JSON.stringify(json, null, 2);
});

In template I use {{stringify entry}}

Tested on Sails v0.12.13

Upvotes: 0

haipham23
haipham23

Reputation: 476

OK, after few hours trying, I come up with a solution:

You can add this line to the end of config/helpers.js

module.exports = Handlebars.helpers;

Inside view.js:

module.exports.views = {
  engine: 'handlebars',
  layout: 'layout',
  partials: 'partials',
  helpers: require('./helpers')
};

It will work.

Upvotes: 2

Related Questions