16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Liquidで配列を作る、要素を追加する

Posted at

配列を作るにはsplitというフィルターを使うしかない。

{% assign beatles = "John, Paul, George, Ringo" | split: ", " %}
{% for member in beatles %}
  {{ member }}
{% endfor %}
John
Paul
George
Ringo

そして、要素を追加するには、文字列として結合してから、最後にsplit: ","する。
Rubyのpush的なものはない。

{% assign words = "" %}
{% assign words = words | append: "John" | append: "," | append: "Paul" |append: "," | append: "George" | append: ","| append: "Ringo" %}
{% assign array = words | split: "," %}

{% for member in array %}
  {{ member }}
{% endfor %}
→上と同じ出力結果

煩雑ですが、しょうがないですね。

ちなみに、
要素を追加するかfor文を回して配列の元になる文字列を結合していく時、条件によって文字列を足すか足さないかすると、,が最後に残ってしまって、正しく配列が生成できなかったりします。
そういった時は、,を文字列の最初に含めて足していって、最後にremove_first: ","するといいです。

{% assign words = "" %}
{% for word in someArray%}
  {% if forloop.index0 == 0 or forloop.index0 == 2 or forloop.index0 == 4 %} {% comment %}この条件文稚拙ですが例としてとりあえず{% endcomment %}
    {% assign words = words | append: "," | append: "word" %}
  {% endif %}
{% endfor %}
{% assign words = words | remove_first: "," %}
{% assign array = words | split: "," %}

forloop.index0 は、for文の中で、何回目の繰り返しなのかを返します(0から始まる。index1 で1から始まる)

##参考
split
https://shopify.github.io/liquid/filters/split/
append
https://shopify.github.io/liquid/filters/append/
remove_first
https://shopify.github.io/liquid/filters/remove_first/
forloop
https://shopify.dev/docs/themes/liquid/reference/objects/for-loops

16
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
16
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?