Skip to content

Instantly share code, notes, and snippets.

@bramaudi
Last active February 8, 2022 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bramaudi/3011b94652a014667dbd5be0d36e5f63 to your computer and use it in GitHub Desktop.
Save bramaudi/3011b94652a014667dbd5be0d36e5f63 to your computer and use it in GitHub Desktop.
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