Search code examples
javascripthtmlalpine.js

cannot access elements when using x-for


I made this code to get a json file and display a field from each of the elements

<script src="https://www.unpkg.com/alpinejs" defer></script>

<script>
  function note(a) {
      console.log(a);
      return a;
  }
</script>

<div x-data="{ bios: [] }",
     x-init="bios = note(await (await fetch('http://localhost:8000/bios.json')).json())">
  <template x-for="h in bios">
    <p>member</p>
    <p x-text="h.Name"></p>
  </template>
</div>

when it loads, the console has the json file in it, but the page just has the word member as many times as there are elements and nothing else


Solution

  • The <template> tag for x-for requires a single root element, try so:

    <template x-for="h in bios">
    
        <div>
            <p>member</p>
            <p x-text="h.Name"></p>
        </div>
    
    </template>
    

    Here you can find the related documentation