如果商品不在购物车中,则显示添加到购物车btn

时间:2020-04-20 05:44:05

标签: shopify liquid

此代码有问题。 我想做的是:

如果产品已经在购物车中>

显示一次“查看购物车”按钮。

其他

显示一次添加购物车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 %}

我需要输出:

如果购物车中有产品,请查看购物车btn一次 要么 如果产品不在购物车中,则添加到购物车btn 谢谢

1 个答案:

答案 0 :(得分:0)

您应该稍微改变逻辑。

{% 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,然后从循环中断开。 (不需要中断,但如果我们已经知道存在中断,则不会循环)

然后,我们仅创建一个if语句来检查not_in_cart是否为真。