Skip to main content

Handelbars.js Example

For these examples to work you will need to install the handlebars.js npm package.

Simple Example

const Handlebars = require('handlebars');

var source = "<p>Hello, my name is {{name}}. I am from {{hometown}}. I have " +
"{{kids.length}} kids:</p>" +
"<ul>{{#kids}}<li>{{name}} is {{age}}</li>{{/kids}}</ul>";
var template = Handlebars.compile(source);

var data = { "name": "Alan", "hometown": "Somewhere, TX",
"kids": [{"name": "Jimmy", "age": "12"}, {"name": "Sally", "age": "4"}]};
var result = template(data);

console.log(result);

Extended Example

  1. Create a file named template.html with the following code.
<!-- template.html -->
<html>
<head>
<title>template.html</title>
</head>
<body>
<div class="header">
<h1>{{custom_title title}}</h1>
</div>
<div class="body">
<p>{{body}}</p>
</div>
<div class="footer">
<div><a href="http://twitter.com/{{author.twitter}}">{{autor.name}}</a>
</div>
<ul>
{{#each tags}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>
</body>
</html>
  1. Create a file named app.js with the following code.
// app.js

const handlebars = require('handlebars'),
fs = require('fs');

const data = {
title: 'Exploring GPT-3',
author: 'Steve Tingiris',
tags: ['openai', 'gpt-3', 'nlp']
}
data.body = process.argv[2];

fs.readFile('template.html', 'utf-8', function(error, source){
handlebars.registerHelper('custom_title', function(title){
var words = title.split(' ');
for (var i = 0; i < words.length; i++) {
if (words[i].length > 4) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
}
title = words.join(' ');
return title;
})

var template = handlebars.compile(source);
var html = template(data);
console.log(html)
});
  1. Run the app.js to test.
node app.js

References