6

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?

1
  • Another option is that, when you hide the div you also disable the input so that it is not sent in the request. Commented Oct 19, 2021 at 12:22

1 Answer 1

8

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>
Sign up to request clarification or add additional context in comments.

2 Comments

I don't understand why adding surrounding div in the templates worked, but I followed your lead and it finally worked. Thank you.
It works due to how Alpine handles templates internally in version 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.