Created
June 17, 2017 21:51
-
-
Save HipsterBrown/bec9237618a45a80379545f74be660de to your computer and use it in GitHub Desktop.
Tiny Streaming Templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
const { Transform } = require('stream'); | |
const eachBlockRegex = /{{\s*#each\s*(.*)}}([\S\s]*?){{\s*\/each\s*}}/g; | |
module.exports = (data = {}) => ( | |
new Transform({ | |
writableObjectMode: true, | |
transform(chunk, encoding, callback) { | |
let html = chunk.toString(); | |
// {{#each}}{{/each}} block support | |
let eachBlock; | |
while ((eachBlock = eachBlockRegex.exec(html)) !== null) { | |
const prop = eachBlock[1]; | |
const template = eachBlock[2]; | |
const compiledBlock = data[prop].map((value) => { | |
return template.replace(/{{\s*value\s*}}/g, value).trim(); | |
}).join('\n'); | |
html = html.replace(eachBlock[0], compiledBlock); | |
} | |
// simple templating support | |
for (const prop in data) { | |
const finder = new RegExp(`{{\\s*(${prop})\\s*}}`, 'g'); | |
html = html.replace(finder, data[prop]); | |
} | |
callback(null, html); | |
}, | |
}) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment