Sails.js with Handlebars — or any other template engine
A quick recipe for configuring Sails.js with handlebars template engine or any other template engines supported by consolidate.js. Handlebars is handy in server side rendering of your pages. In my experience, using a server side template engine over a Single Page Application (SPA) has the benefit of loading super fast. And Speed is essential for
- Reducing Bounce Rate
- Search Engine Ranking
- Driving Conversions
Prerequisites
This recipe considers that you have a basic Sails.js project setup already. Else setup one first.
1. Install Handlebars & Consolidate
Consolidate is a template engine library that helps configure any supported template engines to work with (in our case) Sails.js.
npm i -S handlebars consolidate
2. Configure the Template Engine
Make changes to config/views.js file to use Handlebars
module.exports.views = { extension: 'handlebars', layout: 'layouts/layout', getRenderFn: () => { // Import `consolidate`. var cons = require('consolidate'); // Return the rendering function for Handlebars return cons.handlebars; },};
3. Configure Task
In tasks/config/sails-linker.js file, replace all the occurrences of .ejs
with .handlebars
.
That’s it. A good rule of thumb is to have the latest version of Node.js, and Sailer.js. And don’t forget to restart the server…