Let's copy the app folder we created in the Creating a Hapi web app recipe to the hapi-views folder, install the vision (a Hapi view manager) and ejs modules, and copy the views folder from our main recipe into the hapi-views directory:
$ cp -fr creating-a-hapi-web-app/app hapi-views $ cd hapi-views $ npm install --save vision ejs $ cp -fr ../express-views/views views
At the top of index.js we'll include the vision and ejs modules:
const hapi = require('hapi') const inert = require('inert') const vision = require('vision') const ejs = require('ejs')
Near the bottom of index.js we'll update the plugins we want to register (based on the dev constant):
const plugins = dev ? [vision, inert] : [vision] server.register(plugins, start)
Now we'll call the new server.views method, in our start function with relevant settings:
function start (err) { if (err) throw err server.views({ engines: { ejs }, relativeTo: __dirname, path: 'views' }) routes.index(server) if (dev) routes.devStatic(server) server.start((err) => { if (err) throw err console.log(`Server listening on port ${port}`) }) }
Finally, let's update the route handler in routes/index.js:
module.exports = index function index (server) { server.route({ method: 'GET', path: '/', handler: function (request, reply) { const title = 'Hapi' reply.view('index', {title}) } }) }
The vision plugin decorates the server object by adding a views method, and the reply function with a view method.
When we call server.views in the start function, we set the engines property to an object with a key of ejs containing the ejs module (we used ES2015 shorthand object properties, { ejs } is the same as {ejs: ejs}). The key on the engines object corresponds to the extension used for a given view, if there is only one property of the engines object then it becomes the default view extension. So when we call reply.view with index Hapi knows to assume we mean views/index.ejs.
The vision middleware used for template rendering has a standard interface for hooking in different template engines. See https://github.com/hapijs/vision#examples for several examples of template engines integrating with vision.