Set additional text along with {{ .Title }} in {{ .Scratch }}

So, I’m trying to set page title based on a condition. Since I need to include the same title in properties like og:title, etc. I was thinking, maybe, I could store the title in a variable ({{ .Scratch}}).

Here’s what I am doing:

{{ if .IsHome }}

  {{ .Scratch.Set "title" .Site.Params.Title }}

  {{ else if in (.Scratch.Get "currentPage") "tags" }}

  {{ .Scratch.Set "title" "Projects tagged {{ .Title }} | {{ .Site.Params.Title }}" }}

    {{ else }}

    {{ .Scratch.Set "title" "{{ .Title }} | {{ .Site.Params.Title }}" }}

{{ end }}

<title>{{ .Scratch.Get "title" }}</title>

It’s working correctly except for the fact that in the both the else conditions, it’s setting title as Projects tagged {{ .Title }} | {{ .Site.Params.Title }} as-is. The {{ .Title }} and {{ .Site.Params.Title }} are not getting substituted with the expected values.

I’ve to do something similar for description, so, it’ll be helpful to set it once and access it multiple times.

P.S.: currentPage has been setup like this: {{ .Scratch.Set "currentPage" .Permalink}}

Try to use something like printf. Example:

printf "Projects tagged %s | %s" .Title .Site.Params.Title
1 Like

Also, do you remember this from yesterday?

1 Like

Yeah I do, that’s why I wanted to know the alternative route to do this. I just thought that showing what I tried (basically, what I could think of trying) would be better than asking people to help without me trying anything.


So, I replaced

{{ .Scratch.Set "title" "Projects tagged {{ .Title }} | {{ .Site.Params.Title }}" }}


{{ .Scratch.Set "title" (printf "Projects tagged %s | %s" .Title .Site.Params.Title) }}

and it works great, however the line

{{ .Scratch.Set "title" (printf .Title " %s | %s" .Site.Params.Title) }}

when used as

{{ .Scratch.Set "title" (printf .Title " | " .Site.Params.Title) }},

produces the title as ProjectName%!(EXTRA string= | , string=SiteTitle)

Something to note, ProjectName and SiteTitle come out fine, the problem is the %!(EXTRA string= | , string= that are popping up.

EDIT: Formatted in a more readable way.

Please, read the code and error message carefully. :neutral_face:

Oh, so, the trick was to set is like this:

{{ .Scratch.Set "title" (printf "%s | %s" .Title .Site.Params.Title) }} Basically, all variables after the text in "...". So, I’m guessing %s is what defines where the strings will be placed.

Alright, got it. Thanks guys.

1 Like

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