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

Shopify Liquid循环嵌套if标签语法错误排查求助

解决Liquid语法错误:'endfor' is not a valid delimiter for if tags

问题原因

你在{% assign %}标签内部直接嵌套了{% for %}循环,这违反了Liquid的语法规则——{% assign %}仅支持赋值单一表达式或静态字符串,无法在其中嵌入for、if这类控制流标签。Liquid解析器错误地将循环的{% endfor %}识别为外层{% if %}标签的闭合符,因此抛出该报错。

修复方案

步骤1:用capture捕获循环生成的JSON内容

capture标签可以捕获一段包含Liquid渲染逻辑的输出内容,适合用来生成动态JSON字符串:

{% if settings.limit_quantity or settings.display_inventory_left %}
  {% capture inventoryJson %}[
    {% for v in product.variants %}
      {
        "id": {{ v.id }},
        "inventory_quantity": {{ v.inventory_quantity }},
        "inventory_management": "{{- v.inventory_management -}}",
        "inventory_policy": "{{ v.inventory_policy }}"
      }
      {% unless forloop.last %},{% endunless %}
    {% endfor %}
  ]{% endcapture %}
  {% assign variantInventoryAttr = 'data-variant-inventory="' | append: inventoryJson | append: '"' %}
{% endif %}

先用capture把循环生成的JSON数组存到inventoryJson变量,再拼接成完整的HTML属性字符串赋值给variantInventoryAttr。

步骤2:正确在form标签中添加自定义属性

{% form %}标签的参数仅支持键值对格式,不能直接传入完整的属性字符串,可选择以下两种方式处理:

方式一:直接在form标签内输出属性
{% form 'product', product, id: "product-form-{{ product.id }}", class: "clearfix product_form init {{cssClass}}", data-product-id: "{{ product.id }}" %}
  {{ variantInventoryAttr }}
{% endform %}
方式二:使用form_attributes生成基础属性后追加自定义属性

这种方式能把自定义属性直接写在form标签的起始标签上:

<form {% form_attributes 'product', product %} 
      id="product-form-{{ product.id }}" 
      class="clearfix product_form init {{cssClass}}" 
      data-product-id="{{ product.id }}"
      {{ variantInventoryAttr }}>
  <!-- 表单内容 -->
</form>

关键注意事项

  • 不要在{% assign %}标签内部嵌套控制流标签(for/if等),复杂动态内容必须用capture捕获
  • {% form %}的参数是键值对集合,直接传入属性字符串会触发语法错误,需通过直接输出或form_attributes方式添加自定义属性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 06:17:26