在Liquid中按索引为数组赋值

时间:2017-12-15 15:16:09

标签: shopify liquid

我在一些复杂的循环中,我需要通过索引为数组赋值,这样如果值已经存在,它将替换它,如果不是,它将创建它。

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

{% assign arr = '' | split: '' %}
{% assign arr[index] = value %}

无效,数组仍为空。

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:1)

没有直接的解决方法。

您始终可以使用默认值重新创建数组,但这只会为您提供单个值。

一个潜在的解决方法是重新创建源并填写任何缺失的默认值然后重新拆分为数组

{% 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 -->
相关问题