Best way execute nested html templates

I’m new to go. But so far I’m loving it. I would like to understand the most efficient way to parse html templates.

I have a small web app with a layout template and separate nested content templates. It works just fine if I parse the templates separately in each of the handlers. e.g.

tmpl := template.Must(template.ParseFiles("templates/layout.gohtml", "templates/index.gohtml"))
tmpl.Execute(w, data)

My understanding from what I have read is that it is better to parse all the templates once globally and then execute them by name. e.g.

var templates = template.Must(template.ParseGlob("templates/*"))   // global to package
...
err := templates.ExecuteTemplate(w, "index.gohtml", data)    // in handler

However, it doesn’t seem to work for me. I get a blank page. I assume it’s not doing the nesting. But I’m not sure why it doesn’t work. I can’t seem to find any examples to show this scenario.

What am I missing? Should I just parse them all locally and not worry about it? What is the most efficient way to do it?

Thanks

index.gohtml:

{{define "title"}}Home{{end}}
{{define "content"}}
    <p>Do something...</p>
{{end}}

layout.gohtml: (simplified)

<!doctype html>
<html lang="en">
<head>
    <title>{{template "title" .}}</title>
</head>
<body>
    {{template "content" .}}
</body>
</html>

Note that you may use {{define “content”}} at the beginning.

I did try your approach at first. You can do this, but it is a bit tricky. You have to “embed” the content dynamically.

layout := tpl.Lookup("layout.html")
layout, _ = layout.Clone()
t := tpl.Lookup(path)
if t == nil {
	//404.html
}
_, _ = layout.AddParseTree("content", t.Tree)

head := title.Title(path)
layout.Execute(w, head)

Now I make it simpler the other way around. Use sub templates in the main template. It is easier to maintain. https://gowebstatic.tk/pages

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