在 Liquid 中按索引为数组赋值

art*_*pro 5 liquid shopify

我处于一个有点复杂的循环中,我需要通过索引为数组分配一个值,这样如果该值已经存在,它将替换它,如果不存在,它将创建它。

所以我需要做这样的事情:

{% assign arr = '' | split: '' %}
{% assign arr[index] = value %}
Run Code Online (Sandbox Code Playgroud)

这不起作用,数组仍然是空的。

有什么解决方法可以做到这一点吗?

bkn*_*hts 3

没有直接的解决方法。

您始终可以使用默认值重新创建数组,尽管这只会给您一个值。

一种可能的解决方法是重新创建源并填充任何缺失的默认值,然后重新拆分为数组

{% assign arr = someValue | split: '' %} <!-- splitting to single chars ? -->
{% assign withDefaults = '' %}
{% for ...%}
  {% unless arr[loop.index0] == true %}
  {% withDefaults = withDefaults | append : 'defaultValue,' %}
  {% else %}
  {% withDefaults = withDefaults | append : arr[loop.index0] | append : ',' %}
{% endfor %}
{% assign arr = withDefaults | split: ',' %} <!-- you'll have an extra blank element but that may not matter -->
Run Code Online (Sandbox Code Playgroud)