-
Notifications
You must be signed in to change notification settings - Fork 21
7. Hogan (Replace values from templates)
leonardo Rico edited this page Dec 3, 2017
·
1 revision
install the following npm packages
npm install hogan.js bluebird --save
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);
}
Create template in src/views/templates/example.html
<h1>hi {{name}}!</h1>
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)
}
Nodetomic Api Swagger