[英]Show Add to Cart btn if item is not in cart Shopify
这段代码有问题。 我想做的是:
如果产品已经在购物车中 >
显示一次“查看购物车”按钮。
别的
显示添加购物车 btn 一次
它确实如此,但它打印的就像单个产品的数量(循环中的)是 5,所以它重复添加到购物车 btn 5 次。 无论如何这里我的代码:
{% 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 %}
我需要它 output:
如果产品在购物车中,则查看购物车 btn 一次;如果产品不在购物车中,则添加到购物车 btn 谢谢
你应该稍微改变你的逻辑。
{% 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 %}
我们将not_in_cart
的默认值设置为false
-> {% assign not_in_cart = true %}
之后,我们查看购物车中的商品是否存在,如果存在,我们将变量覆盖为true
并退出循环。 ( break 不是必需的,但如果我们已经知道它的存在,就没有循环的意义)
之后,我们只需创建一个 if 语句来检查not_in_cart
是否为真。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.