简体   繁体   English

如何将 Liquid 数组转换为 Javascript 数组?

[英]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.在我的 Jekyll 站点中,我想从_data/stocks.yml加载数据并在 Chart.js 驱动的图表中使用这些数据。 Chart.js accepts chart datasets and labels as simple Javascript arrays. Chart.js 接受图表数据集和标签作为简单的 Javascript 数组。 Is there an easy way to convert a Liquid array to a Javascript array or map?有没有一种简单的方法可以将 Liquid 数组转换为 Javascript 数组或映射?

I tried doing: var months = {{ site.data.stocks.yml | json }}我试着做: var months = {{ site.data.stocks.yml | json }} var months = {{ site.data.stocks.yml | json }} but I think that only works for individual strings/variables and not collection structures. var months = {{ site.data.stocks.yml | json }}但我认为这只适用于单个字符串/变量而不是集合结构。

The _data/stocks.yml file: _data/stocks.yml文件:

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

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 .第一个是,根据jekyll 文档,您应该使用不带扩展名.yml的格式site.data.datafile访问数据文件。 In your case, you would access your data using {{ site.data.stocks }}在您的情况下,您将使用{{ site.data.stocks }}访问您的数据

The second is that the jekyll (liquid) filter for converting to json is | jsonify二是转成json的jekyll(液体)过滤器是| jsonify | jsonify , not | json | jsonify ,而不是| json | json . | json So to convert your stocks data file to json you would use {{ site.data.stocks | jsonify }}因此,要将您的股票数据文件转换为 json,您将使用{{ site.data.stocks | jsonify }} {{ 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.如果你有一个液体数组,那么我认为简单的方法是循环遍历液体数组并在每次迭代时将元素推入 JS 数组。

Eg:例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM