Using resources.ExecuteAsTemplate with page bundles

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:

  1. Plotting code should be in its own .js files, not inlined
  2. JavaScript code pertaining to a particular page should live close to that page (hence the use of page bundles)
  3. 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.

3 Likes

Thanks for this, great idea.

Inspired by this post, I wrote this proposal:

I thinks that would make you already do easier to do, and would also possibly open up some new possible things to do.

Let me know (and that goes to all of you) if you have any comments/improvements to what I write in the above issue.

Yep, using js.Build and page resources would certainly make this a more elegant solution. Thank you, @bep.