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

Shopify Liquid嵌套循环内If条件失效问题排查求助

问题分析与解决方案

核心问题1:变量类型不匹配

col_id是从(1..5)循环中获取的数字类型,但block.settings.col_position作为Shopify后台的设置项,大概率是字符串类型(比如文本输入框存储的值)。Liquid中数字和字符串直接用==比较会判定为不相等,这就是内层col_position == current_col条件始终不触发的根本原因。

核心问题2:未定义的index变量

代码中多次使用的index没有被赋值,Liquid会将其视为nil:

  • 如果block.settings.position不是nil,position == index这个条件根本不会成立,你不会看到任何<p>标签输出;
  • 如果position恰好是nil,即使进入外层if块,POSITION_IS={{ index }}也只会输出空值。

修正后的代码示例

{% for col_id in (1..5) -%}
  {% for block in section.blocks %}
    {%- liquid
      assign current_col = col_id
      assign position = block.settings.position
      // 将col_position转换为数字,和current_col类型统一
      assign col_position = block.settings.col_position | plus: 0
    -%}
    {% comment %} 用内层循环的索引替换未定义的index,如需外层索引改用forloop.parentloop.index {% endcomment %}
    {%- if position == forloop.index -%}
      <p style="margin:0 10px;">
        if {{ current_col }}=={{ col_position }}
        {%- if col_position == current_col -%}
          POSITION_IS={{ forloop.index }}
        {%- endif -%}
      </p>
    {%- endif -%}
  {% endfor %}
{% endfor %}

关键修正点

  1. 类型统一:通过| plus: 0过滤器将col_position转换为数字,确保和current_col的类型一致,比较逻辑正常生效;
  2. 替换索引变量:用forloop.index(内层循环的当前索引)代替未定义的index,如果需要引用外层循环的索引,使用forloop.parentloop.index。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:40:20