pawanrawal
pawanrawal

Reputation: 93

How to use helpers in Sails v0.11.0 while using handlebars

I want to be using handlebar helper functions with Sails v0.11.0 , but cant understand how to configure them.

There is a solution which works with previous versions helpers in sails , but not sure how it would work in v0.11.0

Upvotes: 2

Views: 966

Answers (3)

Unispaw
Unispaw

Reputation: 158

the simplest solution for people using sailsjs 0.12 is to add a config/helpers.js file that exports the helper functions:

module.exports = {
  ifCond (v1, v2, options) {
    if (v1 === v2) {
      return options.fn(this);
    }
    return options.inverse(this);
  },
  json (context) {
    return JSON.stringify(context);
  }
};

and in the config/views.js file add the following :

helpers: require("./helpers"),

Upvotes: 0

rerich
rerich

Reputation: 277

This is probably not best aproach but it finaly works for me.

When sails is configured to use handlebars it uses express-handlebars package which is installed as dependency. This express-handlebars uses instance of its dependency package handlebars. You need to use registerHelper method on this instance.

I created config/helpers.js with this content:

var handlebars = require("../node_modules/sails/node_modules/express-handlebars/node_modules/handlebars");

handlebars.registerHelper('decorateElement', function (context) {
  return "<span class='red'>" + context + "</span>");
});

Upvotes: 1

Tholle
Tholle

Reputation: 112877

You first need to install handlebars

npm i -S handlebars

Then you just need to register a helper. I like to make a helper.js-file in the config-folder for clarity.

Let's say you want to be able to render json:

var handlebars = require('handlebars');

handlebars.registerHelper('json', function (context) {
  return JSON.stringify(context);
});

Then, in your views you would just write the following:

<script type="text/javascript">

  var object = {{{json example}}};

</script>

Upvotes: 0

Related Questions