shopify - 在 Liquid 中按索引为数组赋值

标签 shopify liquid

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

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

{% 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/

相关文章:

javascript - Shopify 变体链接 - 显示选择的变体图像

shopify - 单个 shopify 元字段的大小限制

jekyll - 如何重置增量?

javascript - 如何修复 Shopify 页面上显示变体时的 JQuery 错误

shopify - Liquid - 将数组转换为小写

markdown - 如何将 Liquid 标签突出显示在有序列表中?

shopify - Shopify 中的售罄选项样式

javascript - SHOPIFY:如何根据特定变体显示 div

javascript - 使用 cURL 访问 API 可以正常工作,但不能使用 Fetch API

shopify - 在 Shopify 主题中自定义同一系列的批量产品