使用metafields变体的相关产品Shopify Liquid

时间:2016-02-05 21:37:12

标签: javascript jquery shopify liquid

我试图利用caroline的相关产品解决方案来构建相关的产品变体。即,当您单击桌面的白色变体时,您将看到椅子的白色变体作为相关产品。 (与将桌面产品链接到椅子产品相反,无论其变型如何。)Caroline的解决方案在这里:https://gist.github.com/carolineschnapp/1003334以下是我的代码。现在它在页面加载时将相同的产品放两次,并且当选择不同的vairant时没有任何反应。我为每个变体格式化元数据值的方法是将" related-product-handle-1,variant-id-1,related-product-handle-2,variant-id-2,related-product- handle-3,variant-id-3"而不仅仅是产品处理。

{% assign image_size = 'compact' %}
{% assign heading = 'Related Products' %}

{% if product.selected_or_first_available_variant.metafields.recommendations.productHandles %}

<h3>{{ heading }}</h3>
<ul class="related-products"></ul>

{% endif %}

<script>!window.jQuery && document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"><\/script>')</script>
{{ 'api.jquery.js' | shopify_asset_url | script_tag }}

<script type="text/javascript" charset="utf-8">  

$(document).ready(function(){

setTimeout(function() {
    var dd = $('.single-option-selector#product-select-option-0');
      var vId = location.search.substring(9);
      switchRelated(vId);

    dd.on('change', function() {
      $('ul.related-products').empty();
      var vId = location.search.substring(9);
      switchRelated(vId);  
    });

    function switchRelated(vId) {
      var list = $('ul.related-products');
      var vIdd = parseInt(vId);
      {% for variant in product.variants %}
        {% if variantId == vIdd %}
          {% if variant.metafields.recommendations.productHandles %}
            recommendations = jQuery.trim({{ variant.metafields.recommendations.productHandles | json }}).split(/[\s,;]+/);
            for (var i=0; i < (recommendations.length); i+=2 ) {
              var j = (i + 1);
              if (recommendations.length && recommendations[i] && recommendations[j] !== '') {
                jQuery.getJSON('/products/' + recommendations[i] + '.js', function(product) {
                  product.variants.forEach(function(variant) {
                    if (variant.id == parseInt(recommendations[j])) {
                      list.append('<li><div class="image"><a href="' + product.url + '?variant=' + recommendations[j] +'"><img src="' + variant.featured_image.src + '" /></a></div><h4><a href="' + product.url + '?variant=' + recommendations[j] + '">' + product.title + '</a></h4></li>'); 
                    }
                  });
                });
              }
            } 
          {% endif %}   
        {% endif %}
      {% endfor %}
    }    
  }, 1);
});
</script>

回答编辑:一旦我对语法错误和一些简短的添加进行了一些修正,第一个非常有帮助。以下是我可能需要的人的答案的编辑版本:

Product.liquid:

 {% for variant in product.variants %}
                {% capture metafield_data %}{% endcapture %}
                {% assign related_products = variant.metafields.recommendations.productHandles | split: '|' %}
                {% for related_product in related_products %}
                  {% assign metafield_items = related_product | split: ',' %}
                  {% assign r_p = metafield_items[0] %}
                  {% assign r_v = metafield_items[1] | plus: 0 %} 
                  {% assign r_n = all_products[r_p].title %}
                  {% for related_variant in all_products[r_p].variants %}
                    {% if related_variant.id == r_v %} 
                      {% assign r_i = related_variant.image.src | img_url: 'small' %}
                    {% endif %}
                  {% endfor %}
                  {% capture metafield_data %}{{metafield_data}}{{ r_p }},{{ r_v }},{{ r_i }},{{ r_n }}{% unless forloop.last %}|{% endunless %}{% endcapture %}
                {% endfor %}
                <option id="{{ variant.id }}" data-metafield="{{ metafield_data }}" {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}">{{ variant.title }} - {{ variant.price | money }}- {{ related_products.size }}</option>
              {% endfor %}

相关变种javascript片段:

$(document).ready(function(){

  setTimeout(function() {
    var dd = $('.single-option-selector#product-select-option-0');
    if(location.search.substring(9) != ''){
      var vId = location.search.substring(9);
     }
     else {
      var vId = {{ product.selected_or_first_available_variant.id }};
     }
    switchRelated(vId);


    $('#product-select option').each(function(index, element){

      $(".single-option-selector#product-select-option-0 option:eq(" + index + ")").attr('id', element.id);
      $('.single-option-selector#product-select-option-0 option:eq(' + index + ')').attr('data-metafield', $(element).attr("data-metafield"));
      $('#product-select option:eq(' + index + ')').attr('id', '');


    });


    dd.on('change', function() {
      var list = $('ul.related-products');
      $(list).children().remove();
       $(list).empty();
      if(location.search.substring(9) != ''){
        var vId = location.search.substring(9);
      }
      else {
       var vId = {{ product.selected_or_first_available_variant.id }};
      }
      switchRelated(vId);  
    });

    function switchRelated(vId) {
      var list = $('ul.related-products');
      $(list).children().remove();
      $(list).empty();
      var vIdd = parseInt(vId);

      console.log(vIdd)
      var variant_matches = $('#' + vId).attr('data-metafield').split('|');

      for (var i=0; i < variant_matches.length; i++) {
          var items = variant_matches[i].split(','); 

          list.append('<li><div class="image"><a href="/products/'+items[0]+'/?variant='+items[1]+'"><img src="'+items[2]+'" /></a></div><h4><a href="/products/' + items[0] + '?variant=' + items[2] + '">' + items[3].replace('_','') + '</a></h4></li>');

      }
    }   
  }, 1);
});

我唯一感到紧张的是,我正在复制“产品选择”中的数据。下拉到“单选项选择器”&#39;落下。我这样做是因为没有用于渲染单选项选择器的模板,它似乎是通过javascript添加的。如果有人对液体操作单选项选择器有任何见解,请告诉我。谢谢!!

1 个答案:

答案 0 :(得分:1)

实现这一目标的最快方法是让Shopify服务器构建用于通过任何AJAX调用拉取链接和图像URL的元素。这是如何做到的。

从您的productHandles示例中,我猜测列表中的3个项目与特定变体ID xxxxxx相关。以这种方式构造元数值

rph-1,rph-v-id-1|rph-2,rph-v-id-2|rph-3,rph-v-id-3

现在在产品液体中找到这个部分

<select class="product-select" id="product-select" name="id" .... </select>

将内部html更改为下面的内容 -

{% for variant in product.variants %}
    {% assign related_products = variant.metafields.recommendations.productHandles | split: '|' %}
    {% for related_product in related_products %}
      {% assign metafield_items = related_product | split: ',' %}
      {% assign r_p = metafield_items[0] %}
      {% assign r_v = metafield_items[1] | plus: 0 %} {% comment %} converting string to number {% endcomment %}
      {% assign r_n = all_products[r_p].title | replace: ' ','_' %}
      {% for related_variant in all_products[r_p].variants %}
        {% if related_variant.id == r_v %} {% comment %} fails if r_v is a string {% endcomment %}
          {% assign r_i = related_variant.image.src }}
        {% endif %}
      {% endfor %}
      {% capture metafield_data %}{{metafield_data}}{{ r_p }},{{ r_v }},{{ r_i }},{{ r_n }}{% unless forloop.last %}|{% endunless %}{% endcapture %}
    {% endfor %}
    <option id="{{ variant.id }}" metafield-data={{ metafield_data }}{% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}">{{ variant.title }} - {{ variant.price | money }}</option>
{% endfor %}

“metafield_data”将包含所有相关产品信息(产品,变体,变体图片)。

JS替换“switchRelated(vId)”

function switchRelated(vId) {
    var list = $('ul.related-products');
    var vIdd = parseInt(vId);

    list.children().remove()

    var variant_matches = $('#vId').attr('metafield-data').split('|')

    for (var i=0; i < variant_matches.length; i++) {
        var items = variant_matches[i].split(',')
        list.append('<li><div class="image"><a href="/products/'+items[0]+'/?variant='+items[1]+'"><img src="'+items[2]+'" /></a></div><h4><a href="/products/'+items[0]+'?variant='item[2]'">'+items[3].replace('_','')+'</a></h4></li>'); 
    }
}    

通俗地说,您从元数据中获取产品句柄和变体ID,并使用液体(服务器端功能)向其添加标题和图像。然后,您将它们与变体匹配,并在您再次使用的元素中分配数据变量以更改html元素。

P.S。代码很长,没有正确对齐,我可能在这里和那里错过了代码标点符号。请检查一下。逻辑很简单,AJAX的全部权重被删除并转移到普通的HTML调用。