Today I realized I’ve overlooked a great feature of Hapi.js, so I figured I’d write a quick post about it.

What I Was Doing

For a server rendered view, I was doing this.

var jade = require('jade');
var fs = require('fs');
var template = jade.compile(fs.readFileSync(pathToTemplate));

// later on
return template(context);

This was fine for what I was doing at the time, since the rendered output was really part of a larger response, and was pretty much the only area in the system where such a thing was being done.

What I Was Doing Today

Instead of having some rendered output as part of a larger API response, I was creating a route that should actually return an HTML view. The above still works fine, but I could see a bit of friction coming in if this project has more views.

  • I would want to set the Content-Type, either through Hapi’s reply.header or reply.type. This could get repetitive.
  • The readFileSync and compile dance could get a bit repetitive or tedious.

What I Do Now

// During the server setup 
  engines: { 
    html: require('jade'),
    path: __dirname + '/templates'

// Later, in handlers
return reply.view('index', context);

Hapi takes care of reading, compiling, and applying the template as long as it’s in the configured path.

More information about what engines are supported and how to use other options can be found by reading up on Hapi’s vision plugin.