Set page title programatically

The content of some pages in my site is generated by reading markdown files stored in 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.


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.


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


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

It worked, thanks @jmooring!

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