What
A theme component to trace which layout files are being used to generate a specific page
Ref: Server option to output templates used? - #4 by jmooring
I was working on a theme component idea about this last year. Real life however got in the way, and I forgot all about it until the topic above.
Why
We don’t currently have a way to trace the templates being called (See: Template call graph ) built in to Hugo.
How
tldr
We trace the layouts being generated by appending opening and closing tags to a .Scratch
variable. Then some JS magic converts this into a tree-like structure, which we can then render, either onto the DOM, or logged to the console.
Details:
For each layout file we are interested in being traced, we add a pair of lines: an opening tag and a matching closing tag.
{{ .Scratch.Add "trace" (slice "<baseof>") }}
... Usual Hugo things ...
{{ .Scratch.Add "trace" (slice "</baseof>") }}
Note the “syntax”: <foo> </foo>
This can be as detailed as you want it to be: you can choose to only annotate the “main” layout files, i.e. index.html
, list.html
, single.html
etc.,
or annotate even the smallest partial file.
Then somewhere in your baseof
file, after the closing annotation, you call the trace partial/s:
{{ partial "__layouttrace/generatetrace" . }}
{{ partial "__layouttrace/rendertrace" . }}
If printing to console.log
is sufficient for your use, you can call only the first partial. The second partial renders a tree in the form of a ul
to the DOM.
Repo here: GitHub - pointyfar/layouttrace
Demo here: https://nervous-ptolemy-2cd2ed.netlify.app/
Demo repo: GitHub - pointyfar/layouttrace-demo
Yes, it’s a lot of work to set up annotating your layouts + partials.
No, you don’t have to have to annotate all the partial files.
No, there is currently (as of today) no way for Hugo to do this for you automatically.
Yes, you need both opening and closing tags.
Comments + suggestions welcome.