How to Exclude Layout Files When Rendering Templates With Node.js and Express

I struggled with this for a good half-hour and I figured I’d share in case anyone else ran into this issue. Long story short, I needed to return an HTML fragment for a particular ajax request from the app (in this case, search results) but the response always included the layout file I configured for the app:

hbsEngine = expressHbs.create({
  extname: 'hbs',
  defaultLayout: 'layout.hbs',
  helpers: {
    formatDate: function (date, format) {
      return moment(date).format(format);

I’d found various blog posts mentioning something about setting layout to false when rendering the template, but they were never really clear about how to disable the layout and pass data to the template.

Here’s how you do just that:

  firstName: req.query.searchTerm
}).toArray(function (err, items) {;
  res.render('components/searchResults.hbs', { layout: false, items: items });

In the above example, items is the property that our template will loop through (via an {{#each}}{{/each}}).

Hope this clarifies things!