首先,我总是喜欢发布可运行的示例,但由于这是 js 和 Shopify 上服务器端渲染液体的混合,我无法获得运行的示例。
在 Shopify 中,您可以从产品模板访问 product 对象,如下所示 {{ Product }} 。
购物车对象有一个 items 属性,它是购物车中所有商品的数组。购物车中的每个 item 对象与 product 对象不同。 product 对象有一个变体列表,而 cart item 对象没有。
这样做的目的是能够编辑购物车中商品的尺寸。
我的问题是,如何才能获得所有链接的变体?您必须转到产品并获取其中所有变体的列表,从变体中获取 product_id。
这很棘手的原因是,当您获得购物车对象的获取响应时,您会为购物车中的每个 item 获得一个 product_id 。但除非您位于产品页面,否则您无法获取产品对象。
只是为了帮助可视化购物车,如下所示:
{
items: [
{
handle: 'product-handle',
product_id: 123,
variant_title: 'product variant'
}
]
}
需要完成的是:
{
items: [
{
handle: 'product-handle',
product_id: 123,
/**
* to get this you need first access to the product object from the product
* template. You could convert the product to json with a filter
* e.g. const product = {{ product | json }} but you don't have the
* opportunity to be on the product template each time you edit a cart item
*/
variants: [
{ color: 'white', size: 's' },
{ color: 'white', size: 'm' }
]
}
]
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
如果您有产品 ID 或句柄,您可以随时致电 Shopify 以获取有关该产品的更多信息,例如分配给该产品的所有变体,以及所有选项。因此,要更改为不同的选项,您需要从购物车中删除变体 ID,然后添加您想要的不同的 ID。您可以使用 StorefrontAPI 调用来获取产品信息。这通常是商家做您需要做的事情的方式。
经过一整天的斗争,我终于明白了。对于曾经遇到过此问题的其他人,您需要执行类似的操作。
从购物车模板中,
cart.liquidconst cart = (() => { const cart = {{ cart | json }} const items = [] let variants {% for item in cart.items %} item = {{ item | json }} variants = [] {% for variant in item.product.variants %} variant = {{ variant | json }} variants.push(variant) {% endfor %} item.variants = variants items.push(item) {% endfor %} cart.items = items return cart })();现在,对于购物车中的每个商品属性,您都有其变体。