Search code examples
javascriptvisualizationechartshugohugo-shortcode

How to load data to generate data visualizations through Hugo shortcodes?


Hugo native shortcodes don't manage data visualizations. However, I found a Hugo theme (DoIt) that handles data visualizations through shortcodes with ECharts. With this theme, ECharts option just has to be inserted in JSON, YAML or TOML format in the ECharts shortcode.

Here is an example:

{{< echarts >}}
{
"xAxis": {
    "type": "category",
    "boundaryGap": false,
    "data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
  },
  "yAxis": {
    "type": "value"
  },
  "series": [
    {
      "data": [820, 932, 901, 934, 1290, 1330, 1320],
      "type": "line",
      "areaStyle": {}
    }
  ]
}
{{< /echarts >}}

Instead of having the data directly within the shortcode, how could I load it from a CSV or a JSON file?

Data in the mentioned example:

|----------+-------|
| category | value |
|----------+-------|
| Mon      |   820 |
| Tue      |   932 |
| Wed      |   901 |
| Thu      |   934 |
| Fri      |  1290 |
| Sat      |  1330 |
| Sun      |  1320 |
|----------+-------|

input.csv:

category,value
Mon,820
Tue,932
Wed,901
Thu,934
Fri,1290
Sat,1330
Sun,1320

input.json:

[
  {
    "category": "Mon",
    "value": 820
  },
  {
    "category": "Tue",
    "value": 932
  },
  {
    "category": "Wed",
    "value": 901
  },
  {
    "category": "Thu",
    "value": 934
  },
  {
    "category": "Fri",
    "value": 1290
  },
  {
    "category": "Sat",
    "value": 1330
  },
  {
    "category": "Sun",
    "value": 1320
  }
]

Solution

  • Try os.Readfile

    Create layouts/shortcodes/load_file.html:

    {{ readFile (.Get "file_name") }}
    

    Then, add the following to your page:

    {{< echarts >}}
    {{< load_file file_name="path/to/input.json" >}}
    {{< /echarts >}}