Using handlebars templates in Sails.js

Let's start by giving you an introdution to Sails.js

What is Sails.js?

Sails makes it easy to build custom, enterprise-grade Node.js apps. It is designed to emulate the familiar MVC pattern of frameworks like Ruby on Rails, but with support for the requirements of modern apps: data-driven APIs with a scalable, service-oriented architecture.

More information can be found here on the Sails.js website.

Switching the template engine

Since v0.10.0 we've had the ability to start a new project by defining what template engine we'd like to use.

We do do that by passing a parameter when we first create out project, like so:

sails new foobar --template=handlebars  

For that to work Sails will need to access the sails-generate-views-handlebars Node module. So if you've not got that installed. Install that first, like so:

npm install sails-generate-views-handlebars -g  

And that should allow us to run the previous command and build us an empty scaffolded Sails.js project using handlebars templates.

N.B. Sails will now use handlebars templates but only with the .handlebars extension. See below for switching to .hbs.

Using .hbs

In order to use a custom file extension, you'll need to specify a custom view engine in the engine property. For .hbs first install handlebars and consolidate, like so:

npm install handlebars && npm install consolidate  

Then in config/views.js in our new Sail.js project, swap out the engine property for the following:

engine: {  
  ext: 'hbs',
  fn: require("consolidate").handlebars
},

Also set the layout parameter to false.

And that should be it. You're now up and running using Handlebars templates with the .hbs extension.