0
votes

having trouble with this code. What i want do is:

if products is already in cart >

show a 'view cart' button once.

else

show add cart btn once

it does but it prints like if quantity of single product (comes in looping) is 5 so its repeats the add to cart btn 5 times. anyway here my code:

  {% for product in collections[collection_].products %}
  <div class="single-product">
    <div class="single-product-image"><img src="{{ product.featured_image.src | img_url: 'large' }}" alt="{{ product.featured_image.alt | escape }}"></div>
    <div class="single-product-details">
      <h3><a href="{{ product.url | within: collection }}">{{ product.title }}</a></h3>
      <div class="product-price">
        <span class="new-price">{{ product.price | money }}</span>
      </div>
    </div>
    <div class="single-product-action">

      {% for item in cart.items %}
        {% if item.product.id == product.id  %}
          <a href="/cart" class="added_to_cart">View Cart</a>
        {% else %}
          {% assign not_in_cart = true %}
        {% endif %}
      {% endfor %}
      {% if not_in_cart %}
        Add to Cart btn
       {% endif %}
    </div>
  </div>
  {% endfor %}

i need it output:

view cart btn once if products is in cart or add to cart btn if product is not in cart Thanks

1
I tried the code from the {% for item in cart.items %} loop on my Debut theme and the button only showed once. Might be missing something else in the code but I wonder if the {% break %} tag would work for you?David Mc
Thanks! It is Solved!Arifurs Dev

1 Answers

0
votes

You should change your logic slightly.

{% assign not_in_cart = true %}
{% for item in cart.items %}
  {% if item.product.id == product.id  %}
    {% assign not_in_cart = false %}
    {% break %}
  {% endif %}
{% endfor %}

{% if not_in_cart %}
  <a href="/cart" class="added_to_cart">View Cart</a>
{% else %}
  Add to Cart btn
{% endif %}

We set the default value for the not_in_cart to be false -> {% assign not_in_cart = true %}

After that we look in the cart items if the items is present, if it is we overwrite the variable to true and break from the loop. ( the break is not required, but no point of looping if we already know it's present )

And after that we just create an if statement to check if the not_in_cart is true or not.