3 minutes
How to Use Highcharts in a Hugo Blog
After viewing Janak’s expertise section, I knew I wanted to add some Highchart graphs to this blog. Janak detailed how he went about doing it in a post, but being new to Hugo and still learning how it works, his post left me with more questions.
After doing a bit more digging and actually reading Hugo’s documentation (RTFM of course!). I learned that my preferred method for implementing Highcharts would be using Hugo’s shortcodes, just like how I am using Codepen and rawhtml for my Credly badges.
When I was looking around I found a Hugo theme for highcharts with the shortcode already setup. Anyways I shamelessly used his code to add my own “highcharts-custom.html” shortcode.
In essence, to add some cool graphs to your Hugo website, add the following in an HTML file in the shorcode directory.
<!--
Based off of https://github.com/cmlnet/hugo-highcharts
-->
<!-- Load highcharts.js -->
{{ if not (.Page.Scratch.Get "highcharts_js") }}
{{ if (fileExists "assets/js/highcharts.js") }}
{{ $script := resources.Get "js/highcharts.js" }}
{{ if hugo.IsProduction }}
{{ $script = $script | minify | fingerprint }}
<script type="text/javascript" src="{{ $script.RelPermalink }}" integrity="{{ $script.Data.Integrity }}"></script>
{{ else }}
<script type="text/javascript" src="{{ $script.RelPermalink }}"></script>
{{ end }}
{{ else }}
<script src="https://code.highcharts.com/highcharts.js"></script>
{{ end }}
{{ .Page.Scratch.Set "highcharts_js" 1 }}
{{ end }}
<!-- Load highcharts-more.js -->
{{ if not (.Page.Scratch.Get "highcharts-more_js") }}
{{ if (fileExists "assets/js/highcharts-more.js") }}
{{ $script := resources.Get "js/highcharts-more.js" }}
{{ if hugo.IsProduction }}
{{ $script = $script | minify | fingerprint }}
<script type="text/javascript" src="{{ $script.RelPermalink }}" integrity="{{ $script.Data.Integrity }}"></script>
{{ else }}
<script type="text/javascript" src="{{ $script.RelPermalink }}"></script>
{{ end }}
{{ else }}
<script src="https://code.highcharts.com/highcharts-more.js"></script>
{{ end }}
{{ .Page.Scratch.Set "highcharts_js" 1 }}
{{ end }}
<!-- Place the chart -->
<div id="{{ .Get "chart" | default "chart" }}" style="min-width: 400px; max-width: 600px; height: 400px; margin: 0 auto"></div>
<!-- Script for the chart -->
<script>
document.addEventListener('DOMContentLoaded', function () {
var myChart = Highcharts.chart('{{ .Get "chart" }}', {
{{ .Inner | safeJS }}
});
});
</script>
After you’ve set that up, in the page you want to add the chart to, just paste your chart JS inside of:
Once that’s done can make cool chart like this:
Hugo Highcharts JavaScript How-To
480 Words
2021-09-28 (Last updated: 2022-01-10)
fe04b95 @ 2022-01-10