Skip to content

Instantly share code, notes, and snippets.

@a2ikm
Created August 9, 2021 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a2ikm/9494c1f984735f38431b70e966b5acc1 to your computer and use it in GitHub Desktop.
Save a2ikm/9494c1f984735f38431b70e966b5acc1 to your computer and use it in GitHub Desktop.
go html/template sandbox
<!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>
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