Skip to content

Instantly share code, notes, and snippets.

@wf9a5m75
Created July 20, 2018 06:40
Show Gist options
  • Save wf9a5m75/4d4122f30f93e26d79572eb0a3e07b6d to your computer and use it in GitHub Desktop.
Save wf9a5m75/4d4122f30f93e26d79572eb0a3e07b6d to your computer and use it in GitHub Desktop.
hapi.js(v17.5.2) + handlebars.js(v4.0.11) with dynamic template load
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/css/test.css">
</head>
<body>
{{ hello }}
</body>
</html>
var Hapi = require('hapi'),
fs = require('fs'),
Handlebars = require('handlebars');
var server = Hapi.server({
"host": "0.0.0.0",
"port": 8080
});
const start = async() => {
await server.register(require('inert'));
await server.decorate('toolkit', 'view', (templateFile, context) => {
// templateFile => 'layout'
// context => {'hello': 'world'}
var txt = fs.readFileSync(`./${templateFile}.html`, 'utf8');
var template = Handlebars.compile(txt);
return template(context);
});
server.route({
"method": 'GET',
"path": "/",
"handler": (req, reply) => {
return reply.view('layout', {
"hello": "world"
});
}
});
server.route({
method: 'GET',
path: '/css/{param*}',
handler: {
directory: {
path: 'template/css',
listing: true
}
}
});
await server.start();
console.log('Server running at:', server.info.uri);
};
start();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment