How to convert Liquid array to a Javascript array?

Viewed 1007

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'
2 Answers

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 }}

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>
Related