我在一个有点复杂的循环中,我需要通过索引为数组分配一个值,以便如果该值已经存在,它将替换它,否则它将创建它。
所以我需要做这样的事情:
{% assign arr = '' | split: '' %}
{% assign arr[index] = value %}
这不起作用,数组仍然是空的。
有什么解决方法可以做到这一点吗?
最佳答案
没有直接的解决方法。
您始终可以使用默认值重新创建数组,尽管这只会给您一个值。
一种可能的解决方法是重新创建源并填充任何缺失的默认值,然后重新拆分为一个数组
{% 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 -->
关于shopify - 在 Liquid 中按索引为数组赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47835139/