Liquid中能否拼接变量并通过循环迭代调用动态命名变量?
Liquid循环中动态关联序号变量的实现方法
Liquid支持变量拼接,你可以通过拼接变量名+迭代序号的方式,动态获取对应Movx和Typex变量的值,具体实现步骤如下:
核心实现思路
- 拼接变量名:用
append过滤器将前缀(如"Mov"、"Type")与循环迭代变量x拼接成完整的变量名字符串。 - 获取变量值:使用
lookup过滤器从对应上下文(如site、page,需根据变量实际存储位置调整)中取出拼接后的变量值。
代码示例
假设你的变量是全局上下文(如site)中的变量,循环范围为1到n:
{% for x in (1..n) %} {% assign mov_key = "Mov" | append: x %} {% assign type_key = "Type" | append: x %} {% assign current_mov = site | lookup: mov_key %} {% assign current_type = site | lookup: type_key %} 第{{x}}次迭代: 动作内容:{{current_mov}},类型:{{current_type}} {% endfor %}
如果变量是当前模板的局部变量,可先将变量存入一个对象中再进行查找:
<!-- 先将所有Mov和Type变量存入对象 --> {% assign var_collection = { "Mov1": Mov1, "Mov2": Mov2, "Type1": Type1, "Type2": Type2 <!-- 依次添加到Movn和Typen --> } %} {% for x in (1..n) %} {% assign current_mov = var_collection["Mov" | append: x] %} {% assign current_type = var_collection["Type" | append: x] %} <!-- 在这里使用current_mov和current_type --> {% endfor %}
通过以上方法,就能在循环的第x次迭代中精准获取Movx和Typex的变量值。
内容的提问来源于stack exchange,提问作者Diogo Almeida
相关产品推荐
相关产品推荐

