Skip to content

Instantly share code, notes, and snippets.

@sonyarianto
Last active December 8, 2018 03:52
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 sonyarianto/0c07470ddbdf816eac627ea34128be75 to your computer and use it in GitHub Desktop.
Save sonyarianto/0c07470ddbdf816eac627ea34128be75 to your computer and use it in GitHub Desktop.
Go template code - loop data on template
package main
import (
"github.com/julienschmidt/httprouter"
"html/template"
"log"
"net/http"
)
func Home(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
// Parse templates.
var templates = template.Must(template.New("").ParseFiles("index4.html"))
type Country struct {
Name string
Population int
}
country := []Country{Country{Name: "Argentina", Population: 300}}
country = append(country, Country{Name: "China", Population: 10000})
country = append(country, Country{Name: "Indonesia", Population: 250})
country = append(country, Country{Name: "Panama", Population: 50})
country = append(country, Country{Name: "Nepal", Population: 30})
// Execute template.
templates.ExecuteTemplate(w, "index4.html", country)
}
func main() {
router := httprouter.New()
router.GET("/", Home)
log.Fatal(http.ListenAndServe(":3000", router))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment