HUGO

Within partial: ability to test if inside a single.html or list.html template

I’ve looked through the discource and the doc and no solution seems ideal. Maybe it is time to request a feature?

It is common to use the same partial with both the list.html and single.html template of a type of page. So we don’t have to create too partials whose only difference would be a few characters (class name, link title instead of simple text title etc…).

For this though, it is important to be able to know if the partial is loaded via the single.html template or list.html template.

Maybe a page variable .Template ?
Or just a simple isList / isSingle function built in the template?

Thanks a ton,

There are already the .IsPage and .IsNode variables. See https://gohugo.io/variables/page/

.IsPage and .IsNode work in baseof.html but not within a partial.
Within a partial .IsPage always returns true while .IsNode always returns false no matter which template (list.html, single.html) you’re using.

Yes they do, but you have to pass the page context to the partial. There is plenty of mention of this in the documentation.

1 Like

Of course, I do it this way (which seems to be the norm):

{{ partial "project/loop.html" dict("pageContext" . "template" "single") }}

where .template allows me to know if it is an archive or a single.

For now I still have the problem with .IsPage, .pageContext.IsPage always returns true from within the partial. I maybe doing something wrong but cannot pinpoint it as of now.

Without having to pass the template variable to the partial, I could eliminate the dict and simply pass the dot. .Title is way cooler that pageContext.Title or even .dot.Title

It’s a small improvement and may make only sense to me, but I’ve seen this “dict” passing an “is_list” or “template” variable alongside the page context in several themes now and I think many could benefit. Other themes bypass this by creating a post-single partial and a post-list partial but when html looks very much the same, it is rather redundant and error-prone.

No matter what happens: As always, thanks for taking the time!

I know its been a little while, but I searched high and low for a solution here that was a little better so I thought I should share mine. Inspired by this post https://regisphilibert.com/blog/2017/04/hugo-scratch-explained-variable/ I managed to get this working by doing the following:

my-partial.html

<div>
    COMMON STUFF
    {{ if eq (.Scratch.Get "scope") "single" }}
    SINGLE STUFF
    {{end}}
</div>

my-list.html

{{ "main" }}
<div>
    STUFF
    {{ range .Pages }}
    {{ .Scratch.Set "scope" "list" }}
    {{ partial "my-partial.html" . }}
    {{ end }}
    OTHER STUFF
</div>
{{ end }}

my-single.html

{{ define "main" }}
{{ .Scratch.Set "scope" "single" }}

<div>
    STUFF
    {{ partial "my-partial.html" . }}
    STUFF
</div>

{{ end }}

Hope this helps anyone else looking for another solution.

2 Likes