Last active
February 8, 2022 08:53
-
-
Save bramaudi/3011b94652a014667dbd5be0d36e5f63 to your computer and use it in GitHub Desktop.
Vanilla JS loop templating based on Array<object>.
This file contains 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
/** | |
* 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