January 04, 2021
Need a simple template parser for the response data. Say no more, fam! This little vanilla puppy can bake-in the data in provided template. This is basically a one-liner, \n’d for readability.
/*** Use the data (containing nested keys) to build the provided template* @param template {String} - template to parse* @param data {Object} - data to bake in template* @returns {String} - compiled template*/const templateParser = (template, data) =>template.replace(/\{\{([\S\s]+?)\}\}/g, (match, path) =>path.trim().split('.').reduce((acc, curr, index) =>!index ? data[next] : acc && acc[next] ? acc[next] : acc,{}))
Example:
const data = {greeting: 'Hello',author: { name: 'Milan' },snippet: { prop: { tag: '#OneDayOfCode' } },}const template = `<p>{{ greeting }}, my name is {{ author.name }} and this is {{ snippet.prop.tag}}.</p>`const compiled = templateParser(template, data)const domChild = document.createRange().createContextualFragment(compiled)// <p>Hello, my name is Milan and this is #OneDayOfCode.</p>document.body.appendChild(domChild)
Written by Milan Miljkovic — a tech enthusiast and design system practitioner.