Skip to content

7. Hogan (Replace values from templates)

leonardo Rico edited this page Dec 3, 2017 · 1 revision

Step 1

install the following npm packages

npm install hogan.js bluebird --save

Step 2

Create a folder called hogan in src/lib/, and inside it create an index.js file with the following code:

import Hogan from 'hogan.js';
import config from '../../config';
const Promise = require('bluebird');
const fs = Promise.promisifyAll(require('fs'));

// Get Template
export async function getTemplate(path) {
  return await (path.indexOf('.js') > -1) ? require(`${config.base}${path}`).default : 
  fs.readFileAsync(`${config.base}${path}`, 'utf8');
}

// Replace in Template
export async function setTemplate(template, values) {
  let HoganTemplate = await Hogan.compile(template);
  return await HoganTemplate.render(values);
}

Step 3

Create template in src/views/templates/example.html

<h1>hi {{name}}!</h1>

Step 4

Use the function to send email from a controller, example from src/api/exampleHogan.js

import { result, error } from 'express-easy-helper';
import { getTemplate, setTemplate } from '../../lib/hogan';
const templateExample = getTemplate('/views/templates/example.html');

export function index(req, res) {

  // Get template
  let template = await templateExample;

  // Values to replaces in template
   let values = {
    name: "Hello World! :)"
  };

  // Replace values in template
  let rendered = await setTemplate(template, values);
  
  // Template with replaced values
  console.log(rendered)

}
Clone this wiki locally