Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure partials and layouts for Handlebars in Sails.js?

I run Sails 0.9.7 and have installed Handlebars which is supported by Consolidate.js and therefore is supported by Sails

I can serve pages from .handlebars files, it works just fine. I can't figure where, in Sails workflow, and in a Sails way, I should register partials, helpers etc... I'm more looking for best practices than just a working solution but any help will be appreciated.

like image 641
Jérémie Parker Avatar asked Nov 06 '13 11:11

Jérémie Parker


1 Answers

I'm running v0.10 beta but this shouldn't affect how I got it working below:

  1. Engine should be handlebars as expected
  2. Routes need to explicitly define controller and action. Setting view won't work. (Unless there's a way I couldn't figure out of setting the partials in the routes file)
  3. Controller needs partials defined as paths relative to the view.

config/views.js

module.exports.views = {
  engine      : 'handlebars',
  layout      : false
};

config/routes.js

'/': {
  controller: 'site',
  action: 'index'
},

SiteController.js

module.exports = {
  // Render Index View
  index: function(req, res) {
    res.view({
      partials: {
        head: 'partials/head',
        tail: '../partials/tail',
      },
    });
  }
};

views/site/index.handlebars

{{> head}}
<h3>SITE INDEX</h3>

views/site/partials/head.handlebars

<h1>HEAD</h1>
{{> tail}}

views/partials/tail.handlebars

<h2>HEAD TAIL</h2>

OUTPUT

<h1>HEAD</h1>
<h2>HEAD TAIL</h2>
<h3>SITE INDEX</h3>
like image 89
rjmoggach Avatar answered Oct 04 '22 20:10

rjmoggach