Change <title> in <head> from a go template

I have a main template layout.html (simplified) with

<head>
    <title>Page title</title> (or {{template "title"}}
</head>
<body>
    {{template "content"}}
</body>

And I want to change the title from the home.html:

{{template "title"}}Home{{"end"}}
<div class="content">
   <p>Some content....</p>
</div>

… and use this dynamic template to set the title:

<head>
    {{template "title"}}
</head>

Of course it does not work. I have found an old post from 2016 that states that “it is not possible to go upwards in the chain. So layout.html gets rendered before home.html , so you cant pass a value back.”

But my question is - if someone figured out how to do this without using any Go code 2019?

1 Like

You can’t change something in a template from other template. This is not how the things works. Take a look over this simple example:

https://schollz.github.io/golang-nested-templates/

Take care to the dot in nested template, won’t work without it (parameters will not arrive in the inside template).

2 Likes

I found a similar solution that works:

BUT, as there are hundreds of templates with different titles, I want to move this to another go file:

main.go (simplifyed)

 data := webtest.Title
 layout.Execute(w, data)

title.go

package title

type Info struct{ Title, Content string }`

func Title() (title string) {
	return (Info{"Your title page", "A classic lorem ipsum content"})
}

But as the return value is a “struct”? it gives an error:

cannot use Info literal (type Info) as type string in return argument

Any tip how to get this to work?

1 Like

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