The use case for this scenario stemmed from including Plotly.js plots in content pages. There are many ways to achieve this, but I wanted to satisfy the following objectives:
- Plotting code should be in its own .js files, not inlined
- JavaScript code pertaining to a particular page should live close to that page (hence the use of page bundles)
- JavaScript code should be able to access other resources (such as CSV data) associated with a particular page bundle
And here’s my implementation. First change baseof.html (or whichever layout you prefer):
{{- partial "pagescripts.html" . -}}
The pagescripts.html partial has the following content, finding all .js files for the page bundle and including them in the html after running them through resources.ExecuteAsTemplate.
{{ $pg := . }}
{{ range (.Resources.Match "**.js") }}
{{ $js := . | resources.ExecuteAsTemplate .Name $pg }}
<script src="{{- $js.RelPermalink -}}"></script>
{{ end }}
Running each script through the Hugo’s resources.ExecuteAsTemplate allows the JavaScript code to access resources within the page bundle as exemplified below (where 1.csv resides somewhere within the page bundle):
{{- $csv1 := .Resources.GetMatch "1.csv" -}}
const path = {{ $csv1.RelPermalink }}
This was a useful way for me to keep all scripts and data for a particular post within a page bundle, so I thought that I would share.