40
votes

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?

4

4 Answers

29
votes

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

8
votes

Is there any other way to do it?

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

1
votes

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.
1
votes

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.