使用Jekyll,如何使用for循环更改数组的内容? [英] Using Jekyll, how do you alter an array's contents using a for loop?
问题描述
说我的作用域中有一个数组thingy.foo = ['abc', 'def']
.
Say I have an array thingy.foo = ['abc', 'def']
in my scope.
我的目标是能够遍历thingy.foo
中的所有项目并对其应用一些条件逻辑,从而覆盖数组中的现有项目...类似这样:
My goal is to be able to loop over all the items in thingy.foo
and apply some conditional logic to it, overwriting the existing item in the array... Something like this:
{% for item in thingy.foo %}
{% assign thingy.foo[forloop.index0] = site.data.lookups[item] | default: item %}
{% endfor %}
我正在做的事情与项目无关,我遇到的问题是更新数组中的项目.该代码编译并运行.在循环中,我可以确认查找"部分正常工作(如果我将其分配给t
并检查t
,那么我将获得一个查找值,但thingy.foo[0]
仍然是原始值).
What I am doing do the item is a bit irrelevant, the part I'm having issues with is updating the item in the array. The code compiles and runs. Within the loop, I can confirm that the "lookup" part works (if I assign it to t
and inspect t
then I get a looked up value, but thingy.foo[0]
is still the original value).
是否可以在Jekyll中更新/覆盖阵列?
Is it possible to update/overwrite arrays in Jekyll?
(这是打算在GitHub Pages上使用的,所以我不能使用自定义插件).
(this is intended for use on GitHub Pages, so I cannot use custom plugins).
推荐答案
看起来您无法对现有数组进行变异...但是您可以遍历初始数组并将项变异为新数组,如下所示:
It looks like you cannot mutate existing arrays... but you can loop over the initial array and mutate items into a new array, like this:
{% assign newArray = '' | split: '' %}
{% for item in thingy.foo %}
{% assign newItem = site.data.lookups[item] | default: item %}
{% assign newArray = newArray | push: newItem %}
{% endfor %}
newArray
现在包含来自thingy.foo
的已更改项目的列表.
The newArray
now contains a list of altered items from thingy.foo
.
这篇关于使用Jekyll,如何使用for循环更改数组的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!