An example of using Hogan.js template engine

Need a template engine? You will need it at some point. So what is the fastest way to get a template engine work. I will suggest Hogan.js works with nodejs.

Let's have a quick tour about Hogan.js.

Get Hogan.js

If you have installed nodejs and npm , type this command to get Hogan.js

 
npm install hogan.js
 

A simple template

Hogan.js uses mustache template language as the template syntax, and its very simple and straightforward. See http://mustache.github.io/mustache.5.html

Here is my simple template file

 
Today is {{macroname}}! Have a {{howwastheday}} day!
 

Compile and render template

Create a test.js file .

 
var hogan = require('hogan.js')
var fs = require('fs')
 
function readFileAsString(file) {
    return fs.readFileSync(file).toString()
}
function getTemplate(file) {
    var template = ""
    // read file as string
    template = readFileAsString(file)
    return template
}
 
var compiledTemplate = hogan.compile(getTemplate('myTemplate.txt'))
 
var context = {
    macroname : 'Sunday',
    howwastheday : 'nice'
}
console.log(compiledTemplate.render(context))
 

It read the template text as a string and then compile and render it.

 
Today is Sunday! Have a nice day!
 

Now, just get through the mustache syntax and try some advanced usage.