by Before Semicolon

Repeating Markup

Making parts of the markup repeat for a list or certain count is always needed in templates in order to save the typing and only manipulate the data. HTML+ allows you to do that using the #repeat attribute which comes with extra associated variables.

Repeat specific number of times

You can repeat a markup for a specific number of times.

<button><span #repeat="3">*</span></button>
<!-- becomes:
<button><span>*</span><span>*</span><span>*</span></button> -->

The $item, $key and $index variables

The #repeat attribute creates three variables for you as context for the markup you are repeating. These are:

<ul>
	<li #repeat="3" class="list-item-{$index}">Item {$item}</li>
</ul>
<!-- becomes:
<ul>
   <li class="list-item-0">Item 1</li>
   <li class="list-item-1">Item 2</li>
   <li class="list-item-2">Item 3</li>
</ul> -->

Repeat for a list or dictionary

The #repeat attribute can also take list-like-objects like Javascript Array and Set as well as dictionaries like Javascript Map and Object.

<div #repeat="[2, 4, 6]">{$index}-{$item}</div>
<div #repeat="new Set([2, 4, 6])">{$item}</div>
<div #repeat="new Map([[a,2], [b,4], [c,6]])">{$key}-{$item}</div>
<div #repeat="{a: 2, b: 4, c: 6}">{$key}-{$item}</div>
<div #repeat="$data.list">$item.name</div>

Repeat as

By default, all item value is available under the $item variable but you can also override it by specifying the as value

<nav>
	<a #repeat="navLinks as link" href="{link.path}">{link.label}</a>
</nav>
<!-- becomes:
<nav>
   <a href="/">Home</a>
   <a href="/about">About</a>
   <a href="/contact">Contact</a>
</nav> -->

It also works for numeric repeats.

<ul>
	<li #repeat="3 as n" class="list-item-{$index}">Item {n}</li>
</ul>
<!-- becomes:
<ul>
   <li class="list-item-0">Item 1</li>
   <li class="list-item-1">Item 2</li>
   <li class="list-item-2">Item 3</li>
</ul> -->