[TIP]: Generate Pages from Remote - Is it possible to generate a JSON file, dynamically, at build time? -

Thanks to @jmooring and @bep I’ve implemented what I needed to. My final solution annexed the ‘generate at build time’ elements.

This example shows the additional files that my current solution refactored to:

assets/build
├── site.json
└── manifest.json

layouts/partials
└── buildTimeResources.html

An example for the contents of buildTimeResources.html would be something like:

{{/* Build-time generated content */}}
{{/* Generated once, by way of '.IsHome' wrapper */}}
{{- if .IsHome -}}

    {{/* Example (using simple string) */}}
    {{/* {{ $j := jsonify (dict "last-build" (now.Format "20060102T150405Z")) }}
    {{ $noop := (resources.FromString "/site.json" $j).Permalink }} */}}

    {{/* Example (using template asset file) */}}
    {{- $j := resources.Get "build/site.json" | minify -}}
    {{- $noop := ($j | resources.ExecuteAsTemplate "/site.json" .).RelPermalink -}}

    {{- $j := resources.Get "build/manifest.json" | minify -}}
    {{- $noop := ($j | resources.ExecuteAsTemplate "/favicon/manifest.json" .).RelPermalink -}}

{{- end -}}

The content of the templates simply include whatever you require, along with any go template code. So, for my simple site.json example mentioned previously, something like:

{
  "build": "{{ (now.Format `20060102T150405Z`) }}",
  "version": "{{ hugo.Version }}",
  "environment": "{{ hugo.Environment }}",
  "commit": "{{ hugo.CommitHash }}"
}

The whole thing is currently kicked off by simply referencing that partial at the bottom (could be anywhere) of layouts/partials/_default/baseof.html

<!DOCTYPE html>
. . .
</html>
{{- partial "buildTimeResources" . -}}

There have been ideas for better syntax for the ability to create the actual files (their creation being a by-product of RelPermalink at present). Something like @bep’s pipe to resources.Publish would be great. It might also be better to be able to kick the whole process off as part of the build (as a 1st class citizen of the build process) rather than jury-rig a hook by way of the baseof.html. However, it works, helped my understanding of the Hugo build process, and I’m very happy with the help and eventual solution. Thanks guys :grin:

4 Likes