You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopify如何用Javascript渲染指定收藏集的前8个商品?

功能实现方案

核心逻辑说明

Liquid 是服务端运行的模板语言,浏览器端无法直接解析 Liquid 语法,你不需要把返回的 JSON 转成所谓的「Liquid 格式商品」,只需要提前预置和站点现有商品卡片结构一致的 HTML 模板,用 JS 把 JSON 数据填充到模板中,再追加到目标节点即可。

步骤1:预置商品模板和容器

在当前页面的 HTML 中加入如下代码,模板结构可以根据你站点现有的商品卡片样式自定义调整:

<!-- 商品卡片模板,不会直接渲染在页面中 -->
<template id="product-card-tpl">
  <div class="product-item">
    <div class="product-img-wrap">
      <img src="" alt="" class="product-main-img">
    </div>
    <h4 class="product-name"></h4>
    <p class="product-price"></p>
    <a href="" class="product-detail-btn">去看看</a>
  </div>
</template>
<!-- 商品渲染容器,动态生成的商品都会放到这个节点里 -->
<div id="render-product-wrap"></div>

步骤2:调整AJAX请求逻辑

给收藏集标题绑定点击事件,请求返回后遍历前8条商品数据填充模板即可:

// 假设收藏集标题的类名为 collection-title,建议给标题加data-handle属性存对应收藏集的handle,方便动态请求
$('.collection-title').click(function() {
  // 动态获取当前点击的收藏集handle,不需要写死MyCollection
  const collectionHandle = $(this).data('handle') || 'MyCollection';
  $.ajax({
    url: `/collections/${collectionHandle}?view=json`,
    type: 'GET',
    dataType: 'json',
    success: function(res) {
      const $renderWrap = $('#render-product-wrap');
      // 清空容器原有内容
      $renderWrap.empty();
      // 取前8个商品
      const showProducts = res.products.slice(0, 8);
      // 遍历渲染每个商品
      showProducts.forEach(product => {
        // 克隆模板内容
        const $card = $($('#product-card-tpl').html());
        // 填充数据,字段对应你接口返回的JSON结构调整即可
        $card.find('.product-main-img').attr('src', product.featured_image.src).attr('alt', product.title);
        $card.find('.product-name').text(product.title);
        $card.find('.product-price').text(`¥${product.variants[0].price}`);
        $card.find('.product-detail-btn').attr('href', product.url);
        // 追加到容器
        $renderWrap.append($card);
      })
    },
    error: function() {
      console.log('商品数据获取失败');
    }
  })
})

内容的提问来源于stack exchange,提问作者Rurohi53

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 08:30:00