shopify - 为现有变量赋值
问题描述
目标是检查购物车中的商品,如果存在,则重新分配 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 %}
解决方案
如果我很了解您尝试实现的目标是在购物车中有特定产品时显示追加销售添加到购物车表单。
首先,正如滴水所解释的那样,您不能重新分配数据库中记录的现有对象属性值。您只能使用 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
推荐阅读
- python - Python - 按其属性对链接列表进行排序
- python - Python中列表列表的反转
- excel - 在 Excel 中将行转换为列
- php - 尝试切断和执行 PHP 生成的 bash 脚本时出现换行问题
- android - PWA 具有持久的 Chrome 通知
- macos - 从 mac 卸载 atom
- jenkins - 在 Jenkinsfile 中签出 scm
- alamofire - Alamofire.download 通过邮寄方式下载,参数不起作用
- angular - 在Angular中单击父组件按钮时验证子组件表单
- java - 如何在spring项目中使用关系路径制作文件对象