Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    hapi.js - View engines


    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.



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    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.

    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 and path to views, the directory where my views are kept.

    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.

    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.

    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.