Howto: Tracing template calls

Hugo uses a set of well-defined rules to determine which template to use to render your content. Still, it’s easy to get confused about what’s happening behind the curtains, so I like to use HTML comments to trace what’s happening. Unfortunately, the Go template strips comments, so you have to use the workaround from the Hugo documentation:

{{ "<!-- a pithy comment -->" | safeHtml }}

Processing the comment as “safeHtml” causes the Go template engine to leave the comment in the output.

To trace my calls, I put enter and leave comments in my templates and partials. For example:

{{ "<!-- hugo: enter section/post.html -->" | safeHtml }}
<body> . . . </body>
{{ "<!-- hugo: leave section/post.html -->" | safeHtml }}

and

<!-- hugo: enter partials/banner.html -->
<header role="banner"> . . . </header>
<!-- hugo: leave partials/banner.html -->

That makes it easy for me to see the order by looking at the page source in the browser:

<!-- hugo: enter section/post.html -->
<body>
<!-- hugo: enter partials/banner.html -->
<header role="banner"> . . . </header>
<!-- hugo: leave partials/banner.html -->
<!-- hugo: leave section/post.html -->
</body>

When I’m working with a theme, I’ll add the theme’s path to the comments. That helps me see when I’m using something from the theme versus an override from my layouts directory.

{{ "<!-- hugo: enter theme/zafta/section/post.html -->" | safeHtml }}
<body> . . . </body>
{{ "<!-- hugo: leave theme/zafta/section/post.html -->" | safeHtml }}

So far, I haven’t made a conscious effort to put this into all my template files. I add the comments when I run into an issue. I do leave them in when I’m done since they’re so useful.

This feels like something that wouldn’t be too hard to add to Hugo as an option, because I’ve wanted the same thing in the past, while developing cabaret.

Thanks @michael_henderson, very helpful.

I suppose you could add a debug = “true” to site params in config.toml, and then do a conditional around these to test for that.