如何在 liquid html 中将一个变量附加到另一个变量名中

How to append a variable inside another vaiable name in liquid html

代码如下:

{% for i in (0..5) %}
  {% assign product = recommendations.top_related_products_{{i}}.products[0].title %}
  {{ product }}
{% endfor %}

此代码抛出错误 Liquid error: Cannot read property '0' of null

我推荐了 6 个数组,例如 top_related_products_0...5

如何打印 top_related_products_0..5 中的标题变量?

创建一个包含变量名称的字符串,然后使用 square bracket notation 访问它。

例如:

{% for i in (0..5) %}
  {% capture related_products %}top_related_products_{{i}}{% endcapture %}
  {{ recommendations[related_products].products.first.title }}
{% endfor %}