Decagrog
Decagrog

Reputation: 97

Inject html with unclosed tags with alpine.js

What is the proper way to inject a portion of html that have unclosed tags?
I use the modulus in x-if for determine when close the row and start a new one.
This code is not working since the template div is immediately closed.

<template x-if="rowCount % 10 === 0"> 
  <div>                                 
  <!-- HTML to inject--> </div><div class="m-0 flex justify-between">  
  </div>
</template>

Upvotes: 0

Views: 564

Answers (1)

Dauros
Dauros

Reputation: 10502

The proper way is to partition the input data to the required shape, then use two loops. Using this method we don't have to deal with unclosed tags and the code is more readable.

<script src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>

<script>
function partition_array(input, amount) {
  let output = [];

  for (let i=0; i < input.length; i += amount) {
    output[output.length] = input.slice(i, i + amount);
  }

  return output;
}
</script>


<div x-data="{array_of_arrays: partition_array([...Array(9).keys()], 3)}">
  <div>
    <template x-for="array in array_of_arrays">
      <div>
        <template x-for="item in array">
        <span x-text="`${item} `"></span>
        </template>
      </div>
    </template>
  </div>
</div>

Upvotes: 1

Related Questions