Skip to content

Instantly share code, notes, and snippets.

@bramaudi
Last active Feb 8, 2022
Embed
What would you like to do?
Vanilla JS loop templating based on Array<object>.
/**
* Loop Templating
* @param {Array<{ [key: string]: unknown }>} data
*/
function maplist($el, data, customRegExp) {
const interpolationRegex = customRegExp || /\[([\w]+)\]/g;
const num = (item, i) => ({i, n: i+1, ...item})
$el._$ = $el._$ || $el.innerHTML;
$el.textContent = '';
$el.innerHTML = data.map(num).reduce((rawTemplate, obj) => {
return rawTemplate += $el._$.replace(
interpolationRegex,
(match, group1) => obj[group1.trim()] ?? match
)
}, '')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment