hapi.js - View engines

Mike Frey
InstructorMike Frey
Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

View engines, or template engines, allow you to maintain a clean separation between your presentation layer and the rest of your application. This video will demonstrate how to use the vision plugin with hapi to enable template support.

[00:00] My hapi server is set up on port 8000, and I've already registered the vision plugin. Vision adds a views method to the hapi server instance. I'll use the views method to configure a view engine. Views takes a single argument that is an object containing an engine's key which is itself an object.

[00:19] The engine's object is a mapping of file extensions to view engines. I'll add an hps key, and require the handlebars module as the value. Now vision will look for the hps file extension when loading views. I also need to tell vision where to find my views. I'll set relative two to underscore, underscore dir.name and path to views, the directory where my views are kept.

[00:46] Next, I need to add a route that will serve my views. Vision adds a view method to the reply object. View takes a view name as the first argument. Notice that I didn't specify the file extension on the view name. Hitting the route route from my browser now renders the Home view, but it looks like something was missing.

[01:07] Looking at the Home.hps file it appeals to be looking for a bit of data called name. I'll add an option name parameter to the route path, then add a data argument to the call to reply view. Using the name param "our world" if name is faulty.

[01:27] Refreshing the browser shows hello world. And if I add Mike to the URL, it will render hello Mike. Vision also supports layouts. I have a layout at hps pile ready to go. It uses content as a placeholder for the rendered view, and includes a bit of styling. To enable layout support, I just need to add layout true to the server views call. Refreshing the browser shows the content wrapped in the layout.

Hoang
Hoang
~ 7 years ago

I am a bit confused by the use of server.register(require('vision', ....) the previous lesion have server.register(require('inert', ...) How do I combine all these registers into the server ?

Granit
Granit
~ 6 years ago

@Hoang: First you have to install these packages with npm i vision handlebars --save then use them as @Mike did.

Markdown supported.
Become a member to join the discussionEnroll Today