Nick
Nick

Reputation: 2911

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

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).

Upvotes: 1

Views: 351

Answers (1)

Nick
Nick

Reputation: 2911

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.

Upvotes: 2

Related Questions