bramaudi

Vanilla JS Looping Template

Table of contents
/**
* Loop Templating
* @param {Array<{ [key: string]: unknown }>} data
*/
function maplist($el, data) {
  const interpolationRegex = /\[([\w]+)\]/g; // usage: [title]
  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
    )
  }, '')
}

Usage

<div id="animelist">
  <div class="user-[i]">[n]. [name]</div>
</div>
maplist(document.getElementById('animelist'), [
  { name: 'Attack On Titan' },
  { name: 'Jojo Bizzare Adventure' },
  { name: 'One Piece' },
  { name: 'Naruto' },
])

Result:

<div id="animelist">
  <div class="user-0">1. Attack On Titan</div>
  <div class="user-1">2. Jojo Bizzare Adventure</div>
  <div class="user-2">3. One Piece</div>
  <div class="user-3">4. Naruto</div>
</div>