Created
June 29, 2017 14:13
-
-
Save mxlje/8e6279a90dc8f79f65fa8c855e1d7a79 to your computer and use it in GitHub Desktop.
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) | |
} | |
} |
thx homie. this was very useful.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
👍🏻