Skip to content

Commit

Permalink
02-Template range
Browse files Browse the repository at this point in the history
  • Loading branch information
bonfy committed Sep 7, 2018
1 parent 9df5fb2 commit 50e5028
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
18 changes: 16 additions & 2 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
Expand Down
4 changes: 4 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -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.