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

Jekyll静态站点中用Liquid实现父产品变体起止范围展示

解决方案

核心实现逻辑是:遍历到variable类型的父产品时,先筛选出所有归属该父产品的variation变体,按position字段升序排序后直接取首尾元素,即可适配任意数量的变体场景,无需硬编码position数值。

修改后的完整Liquid代码

{%- assign printartworks = site.data.products-prints -%}
{%- for printart in printartworks -%}
{%- if printart.type == "variable" -%}

  <h3>{{ printart.id }}</h3>
  <div>
    {% comment %} 筛选当前父产品的所有变体并按position升序排序 {% endcomment %}
    {%- assign variations = printartworks | where: "parent", printart.id | sort: "position" -%}
    {% comment %} 容错处理:仅当存在变体时输出范围 {% endcomment %}
    {%- if variations.size > 0 -%}
      €{{ variations.first.price }} — €{{ variations.last.price }}
    {%- endif -%}
  </div>

  {% comment %} 可选:输出规格名称范围(如 small — xlarge) {% endcomment %}
  {%- if variations.size > 0 -%}
  <div>
    {% assign min_spec = variations.first.id | remove_first: printart.id | remove_first: '-' %}
    {% assign max_spec = variations.last.id | remove_first: printart.id | remove_first: '-' %}
    {{ min_spec }} — {{ max_spec }}
  </div>
  {%- endif -%}
{%- endif -%}
{%- endfor -%}

关键改动说明

  • 用where过滤器直接筛选当前父产品的所有变体,避免多次遍历全量产品数据,性能更优
  • 用sort过滤器按position升序排列变体,完全对齐自定义的规格排序规则
  • 直接调用排序后变体数组的first和last属性取首尾元素,无需硬编码position的固定值,不管变体是2个、4个还是更多都能正常输出正确范围
  • 新增了变体存在性的容错判断,避免父产品无变体时报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:45:05