C&C Docs
Log in
Templates

Lists — x-for

x-for repeats an element once per item in a collection. Use (item, index) for the position and :key to keep DOM nodes stable across updates. The repeated element may be a widget itself — it keeps its own scope, so no wrapper element is needed.

x-for
<ul class="space-y-1" x-data="{ langs: ['Rust', 'Odin', 'JavaScript'] }">
  <li x-for="lang in langs" class="" x-text="lang"></li>
</ul>
Result
  • Rust
  • Odin
  • JavaScript
(item, index) + :key
<ol class="space-y-1" x-data="{ todos: [{ id: 1, text: 'Write' }, { id: 2, text: 'Test' }, { id: 3, text: 'Ship' }] }">
  <li x-for="(todo, i) in todos" :key="todo.id" class="flex gap-2">
    <span class="" x-text="i + 1"></span>
    <span x-text="todo.text"></span>
  </li>
</ol>
Result
  1. 1 Write
  2. 2 Test
  3. 3 Ship
a widget as the item root
<div class=""
     x-data="{ flavours: ['Vanilla', 'Pistachio', 'Espresso'], picked: '—' }">
  <cnc-button
    x-for="flavour in flavours"
    :key="flavour"
    :label="flavour"
    size="sm"
    @click="picked = flavour"
  ></cnc-button>
  <span class="">Picked: <b x-text="picked"></b></span>
</div>
Result
Picked: —