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

如何在Liquid/Jekyll的for循环中传递并使用section变量?

解决Jekyll/Liquid中Include片段循环无法访问变量的问题

问题场景

在Jekyll中复用HTML片段时,父模板的section变量已成功传递到子片段(直接输出变量正常),但无法在for循环的嵌套数据路径中用该变量拼接属性名,导致循环无法执行。

父模板(parent.html)代码:

{% assign section = 'work' %}
{% include child.html %}

原子片段(child.html)代码:

{{ section }} <!-- 正常输出'work' -->
{% for scene in site.data.case-studies.[page.title].{{ section }}-scenes %} 

  <!-- 此循环未执行 --> 
  <!-- 注:已尝试使用括号语法访问section变量 --> 

  {% for image in scene.TopLeft %}
    <img id="top-left-{{ section }}" src="img/{{ section }}/top-left.svg" />   
  {% endfor %}
{% endfor %}

问题核心:无法通过{{ section }}拼接出work-scenes,从而构建正确的循环路径site.data.case-studies.[page.title].work-scenes。

解决方案

Liquid不支持在对象链式访问中直接插入变量拼接属性名,需先通过字符串拼接生成完整的属性键名,再用括号语法访问对应数据:

  1. 先拼接出目标属性的完整键名:
{% assign scenes_key = section | append: "-scenes" %}
  1. 使用括号语法访问嵌套数据(替代链式的.访问):
{% for scene in site.data.case-studies[page.title][scenes_key] %}

修改后的子片段(child.html)代码:

{{ section }} <!-- 正常输出'work' -->
{% assign scenes_key = section | append: "-scenes" %}
{% for scene in site.data.case-studies[page.title][scenes_key] %} 

  {% for image in scene.TopLeft %}
    <img id="top-left-{{ section }}" src="img/{{ section }}/top-left.svg" />   
  {% endfor %}
{% endfor %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 07:46:12