Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Golang html/template recursive rendering partial
type Thing struct {
Text string
Things []Thing
}
func RootHandler(rw http.ResponseWriter, req *http.Request) {
tmpl, err := template.New("root").Parse(`
<html>
{{ define "message" }}
<li>{{ .Text }}
{{ if gt (len .Things) 0}}
<ul>
{{ range .Things }}
{{ template "message" . }}
{{ end }}
</ul>
{{ end }}
</li>
{{ end }}
<ul>{{ template "message" . }}</ul>
`)
data := Thing{
Text: "Hello",
Things: []Thing{
{
Text: "World",
},
},
}
err = tmpl.Execute(rw, data)
if err != nil {
rw.WriteHeader(http.StatusInternalServerError)
fmt.Fprintln(rw, "Error:", err)
}
}
@lj3lj3
Copy link

lj3lj3 commented Apr 21, 2022

👍🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment