Is it necessary to explicitly reference the name when using the Page method?

Hello, I noticed in the default template created with hugo new theme that in the head.html partial, IsHome seems to be part of Page, but .Page is not specified. Is this normal? I also saw that the documentation suggests the same: Description | Hugo

<title>{{ if .IsHome }}{{ site.Title }}{{ else }}{{ printf "%s | %s" .Title site.Title }}{{ end }}</title>

If it’s normal, I suppose I should update the syntax I’ve used in the past:

<meta name="description" content="{{ with .Page.Description }}{{ . }}{{ else }}{{ .Site.Params.description }}{{ end }}">

with:

<meta name="description" content="{{ with .Description }}{{ . }}{{ else }}{{ site.Params.description }}{{ end }}">

The .Description in my example above is taken out from the front matter, if not specified there, then it defaults to the one specified in the hugo.toml file.

Most template types receive a Page object as context. For example, in layouts/_default/single.html the context (the dot) is the Page, so you can do:

{{ .IsHome }}
{{ .Description }}

A notable exception to this is a shortcode template, which receives several things in context such as Params, Page, Site, and more. So, within a shortcode template we would need to do:

{{ .Page.IsHome }}
{{ .Page.Description }}

There is also a Page method on a Page object, which returns the Page object itself. This circular convenience method is useful when creating flexible partial templates that can be called from both a page template and a shortcode template. Doing the below within a single page template is equivalent to the first example above:

{{ .Page.IsHome }}
{{ .Page.Description }}

And yes, that means you can do this too:

{{ .Page.Page.Page.Page.IsHome }}

But don’t.

3 Likes

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.