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

Ruby环境下商品推荐模块Liquid语法错误求助

问题分析与解决方案

错误原因

报错出现在第4行,Liquid不允许在plus过滤器的参数中直接使用布尔比较表达式(比如leftOver > 0、count_product == 1)。这类比较返回的是布尔值,而plus过滤器仅支持数值类型的运算,且这种写法不符合Liquid的语法规则。

修正后的代码

方案1:分步赋值(可读性更强)

{% assign itemsPerColumn = columns | times:1 %}
{% assign perCol = count_product | divided_by: itemsPerColumn | ceil %}
{% assign leftOver = count_product | modulo: itemsPerColumn %}

{% assign add_left_over = 0 %}
{% if leftOver > 0 %}
  {% assign add_left_over = 1 %}
{% endif %}

{% assign add_single_product = 0 %}
{% if count_product == 1 %}
  {% assign add_single_product = 1 %}
{% endif %}

{% assign numCols = perCol | plus: add_left_over | plus: add_single_product %}

{% for row in (1..rows) %}
  <div class="row">
    {% for column in (1..columns) %}
      {% assign index = (forloop.index0 | times: rows) | plus: row | minus: 1 %}
      {% if index < count_product %}
        {% assign product = products[index] %}
        {% include 'product-card', max_height: max_height, product: product, show_vendor: show_vendor %}
      {% endif %}
    {% endfor %}
  </div>
{% endfor %}

方案2:三元表达式(更简洁)

{% assign itemsPerColumn = columns | times:1 %}
{% assign perCol = count_product | divided_by: itemsPerColumn | ceil %}
{% assign leftOver = count_product | modulo: itemsPerColumn %}

{% assign numCols = perCol | plus: (leftOver > 0 ? 1 : 0) | plus: (count_product == 1 ? 1 : 0) %}

{% for row in (1..rows) %}
  <div class="row">
    {% for column in (1..columns) %}
      {% assign index = (forloop.index0 | times: rows) | plus: row | minus: 1 %}
      {% if index < count_product %}
        {% assign product = products[index] %}
        {% include 'product-card', max_height: max_height, product: product, show_vendor: show_vendor %}
      {% endif %}
    {% endfor %}
  </div>
{% endfor %}

修正逻辑说明

两种方案核心都是把布尔比较的结果转换为plus能处理的数值(0或1):

  • 当leftOver > 0时,给numCols加1,否则加0
  • 当count_product == 1时,给numCols加1,否则加0
    这样既保留了原逻辑,又符合Liquid的语法规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 18:22:13