Using templates and validating input in Hapi
In this post we’ll add to our application from the previous set of posts. We’ll be using Vision for template rendering and Joi for input validation.
Vision
Vision adds methods to the Server
, Request
, and ResponseToolkit
interfaces so you can use view engines to render templates. It’s agnostic of the particular engine used; we’ll be using EJS in this post, simply because I’m familiar with it.
Setup
The usual deal with packages:
$ yarn add @hapi/vision ejs
$ yarn add -D @types/hapi__vision @types/ejs
We’ll also need somewhere to put the templates; it’s not very imaginative but I usually use a directory named templates
.
$ mkdir templates
The registerVision
function listed below registers and configures the plugin. The plugin options show which path
to use (in our case templates
). The relativeTo
option says that it lives at the top level, alongside package.json
, not in the source code directory.
One reason for placing the template directory at the top level — if it was in the src
directory, then it would have to be copied to lib
after TypeScript compilation. Not hard but it’s work we don’t need to do.