Accessing static template or rendering template in Hapi Js framework we need some builtin plugins.like 'inert'
In my previous blog how to install Hapi Js I have installed the Hapi Js framework and start with a simple hello world test example.
Now we want to use static template so we need some plugins for that is called "inert" to serve a static page.
So to install the inert plugins we run the following command at command prompt.
npm install inert --save
This will download the inert plugin and add it to the package.json file as a dependency.
Now create a folder "public" inside the hapi folder to put the static file and create a hello.html file to create some html content here.
Then put the following code into the server.js file
'use strict';
const Hapi = require('hapi');
//Create a server with a host and port
const server = new Hapi.Server();
server.connection({
host: 'localhost',
port: 8000
});
//Add the route
server.register(require('inert'), (err) => {
if (err) {
throw err;
}
server.route({
method: 'GET',
path: '/hello',
handler: function (request, reply) {
reply.file('./public/hello.html');
}
});
});
// Start the server
server.start((err) => {
if (err) {
throw err;
}
console.log('Server running at:', server.info.uri);
});
Here we are using the server.register() function for registering the plugin
When you will open the http://localhost:8000/hello your content will display on the browser.
This technique is commonly used to serve images, stylesheets, and static pages in your web application.