How to use Pug with Hapi


hapi nodejs pug Tutorials

This tutorial is compatible with hapi v17. Node and Hapi should be installed for work with this tutorial.

In this quick post I will show how to use a Pug as a default template engine in your Hapi project. We will use information from previous article about how to use handlebars in Hapi. First of all, let’s install the Pug:

npm i pug -s

Setup template engine and render

You need include it to your server and initialize the default template engine for our server. Use the following code:

server.views({
    engines: {
        html: pug
    },
    relativeTo: __dirname,
    path: 'templates'
});

Now, we can start creating a new views. Create an index.html file in templates folder with the following content:

doctype html
html(lang='en')
 head
   title Pug
 body
   h1 #{title}
   div.container
     p #{message}

As you see, we added dynamic content - title and message. We will interpolate these variables inside GET /index route using the view method:

server.route({
    method: 'GET',
    path: '/index',
    options: {
        handler: (req, h) => {
            return h.view('index', {
                title: 'Custom Title',
                message: 'Custom message'
            });
        }
    }
});

Full example

'use strict';

const Hapi = require('hapi');
const Vision = require('vision');
const pug = require('pug');
const Inert = require('inert');

const server = Hapi.server({
    port: 3000,
    host: 'localhost'
});

server.route({
    method: 'GET',
    path: '/index',
    options: {
        handler: (req, h) => {
            return h.view('index', {
                title: 'Custom Title',
                message: 'Custom message'
            });
        }
    }
});

const init = async () => {
    await server.register([Inert, Vision]);
    server.views({
        engines: {
            html: pug
        },
        relativeTo: __dirname,
        path: 'templates'
    });
    await server.start();
    console.log(`Server running at: ${server.info.uri}`);
};

process.on('unhandledRejection', (err) => {
    console.log(err);
    process.exit(1);
});

init();

You can check more information about how to use Pug in the official guide.

Learning Hapi.js? Buy my Hapi.js Handbook🔥

comments powered by Disqus