【问题标题】:Shopify / Liquid - using case / when loop, whilst updating cart item quantityShopify / Liquid - 使用 case / when 循环,同时更新购物车商品数量
【发布时间】:2020-07-05 00:34:35
【问题描述】:

我正在使用以下液体循环:

{%- for option in variant_options -%}
  <li class="product-details__item product-details__item--variant-option" data-cart-item-option>
    {% case option.value %}
      {% when 'S' %}
      Small
      {% when 'M' %}
      Medium
      {% when 'L' %}
      Large
    {% endcase %}
  </li>
{%- endfor -%}

这很好地适用于初始页面加载,但是当您更改购物车中任何产品的数量时,它会使每个购物车项目的 option.value 返回到原始 option.value - 即刷新它们并使其看起来好像 case / when 循环不存在一样。

我怀疑它是由 javascript 驱动的,但欢迎提出任何想法/解决方案。

我正在使用标准的 shopify 首次亮相主题。

【问题讨论】:

  • 您能否提供更多详细信息,例如您在哪里使用代码、预期结果是什么等。

标签: javascript jquery shopify liquid


【解决方案1】:

看起来 Liquid 被用于在初始页面加载时进行模板化,因此这些值不会跟踪用户所做的更改。

Shopify 有一个 AJAX API,您可以在其中获取购物车的内容,因此您可以使用 JavaScript 来执行此操作。

let updateList = () => {
   fetch('/cart.js')
   .then((resp) => resp.json()) // Transform the data into json
   .then(function(data) {
      let i = 0;
      let j = 0;
      let lis = '';
      let optName = '';

      for (i = 0; i < data.items.length; i++) {
         for (j = 0; j < data.items[i]['variant_options'].length; i++) {
            switch(data.items[i]['variant_options'][j]) {
            case 'S':
               optName = 'Small';
               break;
            case 'M':
               optName = 'Medium';
               break;
            case 'L':
               optName = 'Large';
               break;
            default:
               continue;
            };

            lis += '<li class="product-details__item product-details__item--variant-option" data-cart-item-option>' + optName + '</li>';
         };
      };

      //Write lis to page where appropriate
      document.getElementById('element').innerHTML = lis;
      
   })
   .catch(function(error) {
      console.log(error);
   });
};

//Add event handlers to call this function, e.g.:
const btns = document.querySelectorAll('.action_button.add_to_cart, .product-plus.js-change-quantity, .product-minus.js-change-quantity');
let i = 0;

for (i = 0; i < btns.length; i++) {
   btns[i].addEventListener('click', updateList);
};

在上面的代码中,创建了一个函数,它检索购物车内容、遍历它并将您的变体列表写入页面。

然后设置事件处理程序以在单击页面上的相关按钮(添加到购物车、增加数量、减少数量)时调用此函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 2020-12-06
    • 1970-01-01
    • 2015-01-17
    • 2016-04-03
    相关资源
    最近更新 更多