HUGO

Render template trace tree

What

A theme component to trace which layout files are being used to generate a specific page

Screenshot

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.

6 Likes

@pointyfar I just wanted to say this looks really useful and I plan on circle back to it before the end of month, but am currently working on another Hugo related project (updating the exitwp-for-hugo Python script for Python3 and updating it general – it was rather dated and didn’t do everything I want; I am hoping to convert some WordPress sites to Hugo in the next week or so – I decided to experiment with WordPress after using Hugo and got fed up after giving it a good run, but that’s a digression…).

I look forward to incorporating this in the themes I will be working on, and will give you feedback as I do, but it might not be that soon (I know I like to get at least some feedback quickly, hence my reply, even it full feedback will be a while).

1 Like