See which template is used by Hugo


#1

I saw some questions here how to know which template is used by a certain page. Here’s an idea for a partial, which you can integrate in your templates and it shows when it’s used by a page.

Create a show-template.html (could be any name) like this:


<div>
     <p>Template: <span>{{ .Template }}</span> - Kind: <span>{{ .Which }}</span></p>
</div>

This says: Output the variable .Template and output the variable .Which. Declaration of the variables see below.

Now you create a block in your baseof.html where the partial should show up on the rendered page (makes most sense at the top). It’s simple like this:

{{ block "template" . }}{{ end }}

In all your templates (i. e. layouts/_default/list.html or single.html) you define that block and update the respective path of the template:

{{ define "template" }}
  {{ partial "show-template" (dict "Which" .Kind "Template" "layouts/_default/list.html") }}
{{ end }}

//next one could be
{{ define "template" }}
  {{ partial "show-template" (dict "Which" .Kind "Template" "layouts/post/single.html") }}
{{ end }}

//and so on

The Dictionary declares the 2 custom variables from above: “Which” and “Template”. “Which” contains Hugo‘s ˋ.Kindˋ function and “Template” the path of the current template. This is confusing at first but give it a thought and you’ll be amazed what you can do with it.

If you now open a page you can see the template that’s used by that page. If you don’t see the template you expected you are a step further in debugging.

This helps me a lot with debugging. BTW: This is inspired by Mike’s @giraffeacademy Hugo Tutorials which can be found on the Hugo website.

I recently posted something with regards to Hugo’s templates here: My experiences with Hugo’s template lookup order


#2

Cool - Thx for sharing and your very good post!

I prefer to see the chosen templates and partials as comments in the html.
Include e.g.
{{ <!-- _default/terms.html --> | safeHTML }}

or

{{ `<!-- partials/head.meta.html -->` | safeHTML }}

in the templates and partials.

To keep track in the blocks:

{{- block "main" . }}
  {{ `<!-- block main _default/baseof.html  -->` | safeHTML }}
  {{- partial "main.blog.date.html"         . -}}
  {{- partial "main.toc.single.html"        . -}}
  {{ `<!-- back in _default/baseof.html  -->` | safeHTML }}
  {{- .Content -}}
{{- end }}

I had no chance to figure out the lookup order without tracing it via those comments…

working examples:
https://raw.githubusercontent.com/it-gro/hugo-theme-w3css-basic/master/layouts/_default/terms.html
https://raw.githubusercontent.com/it-gro/hugo-theme-w3css-basic/master/layouts/partials/head.meta.html
https://raw.githubusercontent.com/it-gro/hugo-theme-w3css-basic/master/layouts/_default/baseof.html