Created
August 9, 2021 15:43
-
-
Save a2ikm/9494c1f984735f38431b70e966b5acc1 to your computer and use it in GitHub Desktop.
go html/template sandbox
This file contains hidden or 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
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset="UTF-8"> | |
<title>{{.Header.Title}}</title> | |
</head> | |
<body> | |
<h1>{{.Header.Title}}</h1> | |
<ul> | |
{{- range .Posts -}} | |
<li>{{.Title}}</li> | |
{{- end -}} | |
</ul> | |
</body> | |
</html> |
This file contains hidden or 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
package main | |
import ( | |
"html/template" | |
"os" | |
) | |
type Header struct { | |
Title string | |
} | |
type Post struct { | |
Title string | |
} | |
type IndexPage struct { | |
Header Header | |
Posts []Post | |
} | |
func main() { | |
page := IndexPage{ | |
Header: Header{ | |
Title: "index page", | |
}, | |
Posts: []Post{ | |
{ | |
Title: "this is 1st post", | |
}, | |
{ | |
Title: "this is 2nd post", | |
}, | |
}, | |
} | |
f, err := os.Open("./template.html") | |
if err != nil { | |
panic(err) | |
} | |
t := make([]byte, 1024*1024) | |
_, err = f.Read(t) | |
if err != nil { | |
panic(err) | |
} | |
tmpl, err := template.New("template").Parse(string(t)) | |
if err != nil { | |
panic(err) | |
} | |
err = tmpl.Execute(os.Stdout, page) | |
if err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment