Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign an array literal to a variable in Liquid Template

Tags:

jekyll

liquid

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?

like image 603
Stefano Ortisi Avatar asked Mar 31 '14 13:03

Stefano Ortisi


People also ask

How do you assign an array to a liquid?

You can directly create a new empty array controllers and concat to it your controllerName converted into an array using the workaround split:'' . The result is directly an array, without the extra string manipulations.

How do you assign an array value to a variable?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

Can I put variables in an array?

Any variable may be used as an array. There is no maximum limit to the size of an array, nor any requirement that member variables be indexed or assigned contiguously. Arrays are zero-based: the first element is indexed with the number 0.


2 Answers

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


Is there any other way to do it?

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

like image 37
Bart Kiers Avatar answered Sep 20 '22 14:09

Bart Kiers