首页 > 解决方案 > 为现有变量赋值

问题描述

目标是检查购物车中的商品,如果存在,则重新分配 item.product.id 值另一个产品 ID。

分配在我下面的代码中不起作用。输出等于原始值。

{% for item in cart.items %}

{% if item.product.id == 4456879030362 %}
    {% assign item.product.id = 3962085671002 %}
    <div class="upsell-pop" style="text-align:center; width: 100%; border: 1px solid red;">
      <h4>Frequently bought together</h4>
        <p><a href="{{item.product.url}}">{{ item.product.title }}</a></p>
        <img src="{{ item.image.src | product_img_url: 'medium' }}">
        <span class="h3 price text-center">
          {% if item.original_price > item.final_price %}
            <s>{{ item.original_price | money }}</s>
          {% endif %}
          {{ item.final_price | money }}
        </span>
        <form action="/cart/add" data-productid="{{item.product.id}}"  method="post"> 
            <input type="hidden" name="id" data-productid="{{item.product.id}}" class="product-select" value="{{ item.product.variants[0].id }}" data-variant-title="{{ item.product.variants[0].title }}" />
            <input type="submit" value="Add To Cart" />
        </form>
    </div>
{% endif %}

{% endfor %}

标签: shopifyliquid

解决方案


如果我很了解您尝试实现的目标是在购物车中有特定产品时显示追加销售添加到购物车表单。

首先,正如滴水所解释的那样,您不能重新分配数据库中记录的现有对象属性值。您只能使用 assign 标签创建新变量。

但好消息是你不需要做你想做的事。

然后,在 Shopify 中,对象的键是句柄属性而不是 ID 属性。例如,要获取特定产品,您可以通过其句柄进行操作:

{{ all_products['my-product-handle'].title }}

您还必须考虑到在以下条件下使用字符串时需要添加引号:

{% if product.handle == 'foo' %}

所以,为了实现你的目标,你可以试试这个:

{% for item in cart.items %}
  {% if item.product.handle == 'my-upsell-trigger-product-handle' %}
   {% assign upsell_product = all_products['my-upsell-product-handle'] %}
     {{ upsell_product.title }}
     {% form "product", upsell_product %}
        <input type="hidden" name="id" value="{{ upsell_product.selected_or_first_available_variant.id }}">
        <input type="submit" value="Add to cart" />
      {% endform %}
  {% endif %}
{% endfor %}

未经测试,但这应该可以工作!

高温高压

有用的文档:

手柄:https ://help.shopify.com/en/themes/liquid/basics/handle

基本运算符:https ://help.shopify.com/en/themes/liquid/basics/operators#basic-operators

全局对象:https ://help.shopify.com/en/themes/liquid/objects#global-objects

添加到购物车表格:https ://help.shopify.com/en/themes/development/templates/product-liquid#build-the-html-form


推荐阅读