Skip to content

Instantly share code, notes, and snippets.

@bilashcse
Created May 19, 2019 17:43
Show Gist options
  • Save bilashcse/5c5121722c69ea7737f86064a21e3ea1 to your computer and use it in GitHub Desktop.
Save bilashcse/5c5121722c69ea7737f86064a21e3ea1 to your computer and use it in GitHub Desktop.
Generate Dynamic html using NodeJs
function generateDynamicHtml(data, htmlUrl, html) {
let htmlTemplate = htmlUrl ? fs.readFileSync(path.join(__dirname, htmlUrl), 'utf8') : html;
let reg = /<script\b[^>]*>([\s\S]*?)<\/script>/gm;
let match,
arrValues = [],
templateMap = {};
for (var key in data) {
if (Array.isArray(data[key])) {
arrValues.push({
key: key,
values: data[key]
});
}
}
while ((match = reg.exec(htmlTemplate))) {
let templateName = /({{.*}})/
.exec(match[1])[0]
.replace(/{{|}}/g, '')
.split('.')[0];
templateMap[templateName] = match[1];
}
arrValues.forEach(val => {
let templateHtml = templateMap[val.key];
let updatedHtml = '';
val.values.forEach(d => {
let temp = templateHtml;
for (var key in d) {
temp = temp.replace('{{' + val.key + '.' + key + '}}', d[key]);
}
updatedHtml += temp;
});
data[val.key] = updatedHtml;
});
return misc.replaceKeysInHtml(htmlTemplate, data);
}
module.export = {
generateDynamicHtml
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment