40

The only way i know to create an array from my liquid template is:

{% assign my_array = "one|two|three" | split: "|" %}

Is there any other way to do it?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Stefano Ortisi
  • 5,288
  • 3
  • 33
  • 41

4 Answers4

31

Frontmatter

This is a good workaround, add to the top of your file:

---
my_array:
  - one
  - two
  - three
---

then use it as:

{{ page.my_array }}

Analogous for site wide site.data.my_array on the _config or under _data/some_file.yml.

Jekyll 3 update for layouts

If the frontmatter is that of a layout, you need to use:

{{ layout.style }}

instead. See: https://stackoverflow.com/a/37418818/895245

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
8

Is there any other way to do it?

Nope, your split filter is the way to do it.

Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • correct. You must use `split`. Shopify docs on liquid array: https://docs.shopify.com/themes/liquid-documentation/basics/types#arrays – Danny Apr 23 '15 at 00:18
2

Here's another way to do it by first using capture as a friendly way to assign newline-separated values to a variable and then converting that variable to an array with assign and a few filters:

{% capture my_array %}
one
two
three
{% endcapture %}

{% assign my_array = my_array | strip | newline_to_br | strip_newlines | split: "<br />" %}

The filters do the following:

  1. strip removes the leading whitespace before one and the trailing whitespace after three.
  2. newline_to_br replaces newlines with <br /> tags.
  3. strip_newlines removes possible extraneous newlines.
  4. split converts the string into an array, using <br /> as a separator.
Asbjørn Ulsberg
  • 8,721
  • 3
  • 45
  • 61
1

If you put the array in the page frontmatter like:

---
my_array:
  - one
  - two
  - three
---

I have tested that you could simply write it like so:

---
my_array: [one,two,three]
my_prime: [5,7,11,13,17,19]
---

Both of {{ page.my_array }} and {{ page.my_prime }} will output correctly.

eQ19
  • 9,880
  • 3
  • 65
  • 77