Category Archives: Web Programming

sails.js how to use handlebars, and also register helpers for global use

Sails.js is a very good MVC type server solution, it quickly generate restful api and can also respond to CRUD request. However it by default only supports ejs template.

There are many solutions to change it so that it also support handlebars template. Then if you have index.handlebar file in the View folder, it would recognize it.

However I have been searching for a while about is the helper and partial. Handlebars comes with registerHelper function and registerPartial function, which create partial and helper that you can use globally in every *.handlebar file.

For example
handlebars registerHelper('script',function(data,option){
return <script src="/public/css/+data+">;
}

Then in your template you simply put
{{script "mydesign.css"}}

In the webpage it will generate
<script src="/public/css/mydesign">

This is very convinient, but I couldn't find where to register this global helper. There are only options to pass it in as local helper.

Finally I found out how to do it, so here it is:
1. create a helper.js in the /config/ folder.
2. the handlebars object is stored in
var handlebars=require('sails/node_modules/express-handlebars/node_modules/handlebars');
3. register helpers on this handlebars object.