Assign an array literal to a variable in Liquid Template
Asked Answered
B

4

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?

Bearish answered 31/3, 2014 at 13:43 Comment(0)
B
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://mcmap.net/q/408735/-can-you-use-jekyll-page-variables-in-a-layout

Blight answered 3/12, 2014 at 18:18 Comment(3)
Another option is to create a file named "_data/my_array.yml" and put inside the contents: " - one - two - three". Then, it is accessible via site.data.my_array as you said.Tamie
why create it in template directly is prohibited?Mnemonics
@Adi don't know exactly. In general Liquid is crippled by design to allow running untrusted templates.Blight
C
8

Is there any other way to do it?

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

Confidence answered 7/4, 2014 at 19:34 Comment(1)
correct. You must use split. Shopify docs on liquid array: docs.shopify.com/themes/liquid-documentation/basics/…Kapellmeister
V
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.
Vidovik answered 17/12, 2018 at 6:18 Comment(0)
I
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.

Isle answered 30/3, 2021 at 6:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.