For loop shows all values for each cart item within if statement

For loop shows all values for each cart item within if statement

dressinnus
Visitor
1 0 0

Hello,

I would like to show conditional metafield for each cart item added inside cart. I created a for loop with if condition. code is working but for loop prints all metafields for each cart item rather than relevant metafield value. See the attached screenshot. Thanks for the help

 

{% for item in cart.items %}
{% if item.variant.metafields.variant.stocked_sku %}
    <p>Usually Ships in {{ item.variant.metafields.variant.stocked_lead_time }} Days</p> 
 {% else %}  
   <p>Made to Order: Usually Ships in {{ item.variant.metafields.variant.mto_lead_time }} Days</p>
 {% endif %}  
{% endfor %}

 

Screen Shot 2021-12-23 at 12.32.42 AM.png

Replies 2 (2)

Jason
Shopify Partner
11207 226 2317

Why is your code within a for loop?


The cart page would already be looping over the items so it looks like you are adding a second loop that isn't needed. Do you get better results if you remove the for loop and just leave the contents of it?

 

Your code also assumes that either of those metafields exist and it might not always be the case. Adding something to catch that (and just skip showing anything) would be a good idea.

★ I jump on these forums in my free time to help and share some insights. Not looking to be hired, and not looking for work. http://freakdesign.com.au ★

justin456770
Tourist
12 0 0

I also want to know how to solve this problem!

banned