Skip to content

Instantly share code, notes, and snippets.

@mxlje
Created June 29, 2017 14:13
Show Gist options
  • Save mxlje/8e6279a90dc8f79f65fa8c855e1d7a79 to your computer and use it in GitHub Desktop.
Save mxlje/8e6279a90dc8f79f65fa8c855e1d7a79 to your computer and use it in GitHub Desktop.
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

👍🏻

@angelacastaneda
Copy link

thx homie. this was very useful.

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