Set page title programatically

The content of some pages in my site is generated by reading markdown files stored in gist.github.com when the site builds. I want to do the same with the page title.

Working page (hardcoded title):

---
date: 2021-03-12
title: WFH bingo
---

<!-- render gist as article -->
{{< gist-article "9665dc266ce6b76c2e6dc177b790f1bb" >}}

Attempt 1:

Using a shortcode in the front matter:

---
date: 2021-03-12
title: {{< gist-title "9665dc266ce6b76c2e6dc177b790f1bb" >}}

...

I got an error failed to unmarshal YAML: yaml: invalid map key: map[interface {}]interface {}{"< gist-title \"9665dc266ce6b76c2e6dc177b790f1bb\" >":interface {}(nil)}

Attempt 2:

Trying to change the value of .Page.Title:

{{ .Page.Title := "new title" }}

It raises an error unexpected ":=" in operand.

Thanks!

Attempt 1 failed because you cannot use template code or shortcodes in front matter. The only exception to this is within archetypes, where you can use template code but not shortcodes.

Attempt 2 failed because page properties are immutable.

If you really want to do this…

1) Set a page-scoped Scratch within your shortcode:

{{ .Page.Scratch.Set "page_title" "foo" }}

2) Retrieve the Scratch value when needed, making sure that you first render the .Content so that the shortcode is rendered before you try to access the Scratch.

layouts/_default/baseof.html

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, minimum-scale=1.0, initial-scale=1.0">
  <title>
    {{ $noop := .Content }}
    {{ with .Scratch.Get "page_title" }}
      {{ . }}
    {{ else }}
      {{ .Title }}
    {{ end }}
  </title>
</head>

layouts/_default/single.html

{{ $noop := .Content }}
{{ with .Scratch.Get "page_title" }}
  <h1>{{ . }}</h1>
{{ else }}
  <h1>{{ .Title }}</h1>
{{ end }}
3 Likes

It worked, thanks @jmooring!

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