johnpitchko
johnpitchko

Reputation: 159

How to convert Liquid array to a Javascript array?

In my Jekyll site, I want to load data from _data/stocks.yml and use the data in a Chart.js-powered graph. Chart.js accepts chart datasets and labels as simple Javascript arrays. Is there an easy way to convert a Liquid array to a Javascript array or map?

I tried doing: var months = {{ site.data.stocks.yml | json }} but I think that only works for individual strings/variables and not collection structures.

The _data/stocks.yml file:

- month: Jan '20
  portfolio: '-4.5'
  spy: '-0.16'
- month: Feb '20
  portfolio: '-19.2'
  spy: '-8.41'
- month: Mar '20
  portfolio: '-19.1'
  spy: '-12.51'

Upvotes: 3

Views: 2442

Answers (3)

Wakil Ahmed
Wakil Ahmed

Reputation: 1393

The approach will be different based on data type:

<script>
  {% for item in liquid_array %}
    variantsInventoryQty.push({{ item.int_data }})
    variantsInventoryPolicy.push("{{ item.string_data }}")
  {% endfor %}
</script>

Upvotes: 0

Musaib Mushtaq
Musaib Mushtaq

Reputation: 631

If you have a liquid array, then I think the simple way would be looping through the liquid array and pushing elements into the JS array on each iteration.

E.g.:

<script>
let js_array =[];
  {% for item in liquid_array %}
     js_array.push({{item}});
  {% endfor %}
console.log(js_array);
</script>

Upvotes: 0

DHamrick
DHamrick

Reputation: 8488

I think there are two issues with what you're trying to accomplish.

The first is that that, according to the jekyll documentation, you should access a data file using the format site.data.datafile without the extension .yml. In your case, you would access your data using {{ site.data.stocks }}

The second is that the jekyll (liquid) filter for converting to json is | jsonify, not | json. So to convert your stocks data file to json you would use {{ site.data.stocks | jsonify }}

Upvotes: 4

Related Questions