rubo77
rubo77

Reputation: 20835

Skip a loop in alpine.js with x-if

I use this loop

<form action="/" method="POST">
    <template x-for="(deck, index) in $store.cart.decks">
      <div x-show="$store.cart.total(index) > 0">
        <div><span x-text="$store.cart.total(index)"></span> Karten</div>
        <div x-text="deck.price"></div> €
        <input :name="'deck[' + index + '][name]'" :value="$store.cart.decks[index].name">
      </div>
    </template>
</form>

Which works fine and displays all items in my cart and hides those that have a total of 0.

But this will only set the item with 0 on display:none, which will still transfer the data in the POST request.

  1. I tried to use x-if instead of x-show but that is only allowed on a tempate tag.

  2. I tried to add the x-if on the template tag:

    <template x-show="$store.cart.total(index) > 0" ...
    

    this results in an error, because index is not set at that point

  3. I tried to add another <template> tag inside the existing template, but then the variables index and deck are not available inside the second any more

How do I prevent the zero cart items being computed in my POST request?

Upvotes: 6

Views: 5086

Answers (1)

Hugo
Hugo

Reputation: 3888

I think something like the following would work, note the div inside both template elements.

<template x-for="(deck, index) in $store.cart.decks">
  <div>
    <template x-if="$store.cart.total(index)">
      <div>
        <!-- rest of the content -->
      </div>
    </template>
  </div>
</template>

Upvotes: 7

Related Questions