问题
Say I have an array thingy.foo = ['abc', 'def']
in my scope.
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 %}
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).
Is it possible to update/overwrite arrays in Jekyll?
(this is intended for use on GitHub Pages, so I cannot use custom plugins).
回答1:
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 %}
The newArray
now contains a list of altered items from thingy.foo
.
来源:https://stackoverflow.com/questions/56211971/using-jekyll-how-do-you-alter-an-arrays-contents-using-a-for-loop