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.