【问题标题】:Show Add to Cart btn if item is not in cart Shopify如果商品不在购物车中,则显示添加到购物车 btn Shopify
【发布时间】:2020-04-20 05:44:05
【问题描述】:

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

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

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

其他

显示添加购物车 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 谢谢

【问题讨论】:

  • 我在 Debut 主题上尝试了 {% for item in cart.items %} 循环中的代码,但按钮只显示了一次。代码中可能缺少其他内容,但我想知道 {% break %} 标签是否适合您?
  • 谢谢!解决了!

标签: shopify liquid


【解决方案1】:

你应该稍微改变你的逻辑。

{% 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 是否为真。

【讨论】:

  • 谢谢!这个想法很棒。必须以某种方式改变一些事情:{% assign _in_cart = false %} {% for item in cart.items %} {% if item.product.id == product.id %} {% assign _in_cart = true %} {% break %} {% endif %} {% endfor %} {% if _in_cart %} 查看购物车 {% else %} 添加到购物车 btn {% endif %}
猜你喜欢
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-19
相关资源
最近更新 更多