Using Jekyll, how do you alter an array's contents using a for loop?

二次信任 提交于 2021-02-08 09:57:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!