Golang html/template recursive rendering partial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍🏻