如何将原始值传递给JS Shopify

问题描述

我想显示我的库存到使用AJAX原始代码的购物车中,并且在传递某些值方面需要帮助。

1。 当前在我的ajax-cart-template.liquid上,我可以通过使用以下语法进行调用来从theme.js.liquid中获取值:{{cartIndex}} 在theme.js.liquid中定义的

$.each(cart.items,function(index,product) {
  
            var prodImg;
            if (product.image !== null) {
              prodImg = product.image.replace(/(\.[^.]*)$/,"_180x$1");
            } else {
              prodImg = //
            }
  
            if (product.properties !== null) {
              $.each(product.properties,function(key,value) {
                if (key.charat(0) === '_' || !value) {
                   delete product.properties[key];
                 }
              });
            }
  
            animation_row+=2;
  
            item = {
              key: product.key,url: product.url,img: prodImg,animationRow: animation_row,name: product.product_title,variation: product.variant_title,properties: product.properties,itemQty: product.quantity,price: theme.Currency.formatMoney(product.price,theme.settings.moneyFormat),discountedPrice: theme.Currency.formatMoney((product.price - (product.total_discount/product.quantity)),discounts: product.discounts,discountsApplied: product.price === (product.price - product.total_discount) ? false : true,vendor: product.vendor,invStock: product.variant.inventory_quantity,cartIndex: index
            };
  
            items.push(item);
          });

但是,如果我拨打{{invStock}},该按钮将不起作用。有什么原因吗?

2。

我尝试转到ajax-cart-template.liquid并结束{% raw %}并可以调用对象本身,但是我需要索引,我可以从{{ cartIndex }}获得该索引。但是,我不知道如何将{{ cartIndex }}传递给以下代码

<div class="testing">
{% endraw %}
cart.items[{{cartIndex}}].variant.inventory_quantity
{% raw %}
</div>

我将如何解决这个问题?

解决方法

您必须了解Shopify的工作原理。 Liquid在Shopify上呈现,并以HTML,JS和CSS的巨大字符串形式倾倒到浏览器中。

因此,当您尝试使用JS时,您将在Liquid渲染之后运行代码。因此,如果您需要从Liquid中获取一些数据,将其呈现为数据结构,则可以在Javascript出现在前端时稍后使用。

{%raw%} {%endraw%}的典型用法是当您尝试输出模板或某些其他具有Liquid渲染会破坏字符的数据时。因此,您可能不必为此担心。