Mention title on page using template

From the documentation, I would have thought that I could get the title to display in a page produced by a template using {{ .Title }}. It doesn’t work.

For example, if I use the following template test.md

---
title: "Example {{ replace .Name "-" " " | title }}"
date: {{ .Date }}
---

{{ .Title }}

and run hugo new test/one.md, I thought Hugo would produce the title on page one.md. Instead it returns an error:

Error: Failed to process archetype file “test.md”:: execute of template failed: template: test:6:3: executing “test” at <.Title>: can’t evaluate field Title in type create.ArchetypeFileData

It also doesn’t work with {{ .Page.Title }}, nor {{ $.Title }}, nor any of the other variations I tried.

The replace .Name code is drawn verbatim from the documentation.

What is going wrong here? How else could I get the page title in this context?

To clarify, are you expecting the archetype to replace {{ .Title }} with the title set in front matter, when you use hugo new?

So here’s what happens: when you build your site, the front matter in your content is assigned to variables, one of which is .Title. But in archetypes you aren’t building content, you are just creating a new text file; you can’t get .Title because your content doesn’t exist yet.

What you can do is use the same code to get the same result as you will be assigning the title once the file is created. So in your example:

---
title: "Example {{ replace .Name "-" " " | title }}"
date: {{ .Date }}
---

{{ replace .Name "-" " " | title }}

Note the title after the pipe refers to the function for making title case.

2 Likes

Aha, I see. That makes sense. I figured that because the title had been generated when dealing with the metadata, that that metadata would then be available for use later on the page.