Skip to content
Permalink
Browse files

02-Template range

  • Loading branch information...
bonfy committed Sep 7, 2018
1 parent 9df5fb2 commit 50e5028870d4ab7918d391007162c4387540f165
Showing with 20 additions and 2 deletions.
  1. +16 −2 main.go
  2. +4 −0 templates/index.html
18 main.go
@@ -10,16 +10,30 @@ type User struct {
Username string
}

// Post struct
type Post struct {
User User
Body string
}

// IndexViewModel struct
type IndexViewModel struct {
Title string
User User
Posts []Post
}

func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
user := User{Username: "bonfy"}
v := IndexViewModel{Title: "Homepage", User: user}
u1 := User{Username: "bonfy"}
u2 := User{Username: "rene"}

posts := []Post{
Post{User: u1, Body: "Beautiful day in Portland!"},
Post{User: u2, Body: "The Avengers movie was so cool!"},
}

v := IndexViewModel{Title: "Homepage", User: u1, Posts: posts}
tpl, _ := template.ParseFiles("templates/index.html")
tpl.Execute(w, &v)
})
@@ -8,5 +8,9 @@
</head>
<body>
<h1>Hello, {{.User.Username}}!</h1>
{{range .Posts}}
<div><p>{{ .User.Username }} says: <b>{{ .Body }}</b></p></div>
{{end}}

</body>
</html>

0 comments on commit 50e5028

Please sign in to comment.
You can’t perform that action at this time.