GoLang: How to render a web template using Gin framework and render data from map ?

 I have struggled lot of time, to break this into working modal. So below code, is working example where you can have your data in a slice of URLs and render that data using Go Templates. 

I am giving a skeleton HTML template, not adding any thing extra. 

I believe the code itself is self explanatory, if any questions, please dont hesitate to ask.


main.go

package main

import (
"log"
"net/http"

"github.com/gin-gonic/gin"
)

type URL struct {
Name string
Url string
}

var URLs = []URL{
{Name: "google", Url: "google.com"},
{Name: "yahoo", Url: "yahoo.com"},
{Name: "gmail", Url: "gmail.com"},
}

func main() {

router := gin.Default()
router.LoadHTMLGlob("templates/*")
router.GET("/", bookmarks)
router.GET("/hello", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
"Items": URLs,
})
})

log.Fatal(router.Run(":8000"))
}

func bookmarks(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Bookmarks",
"URLs": URLs,
})
}

Go Templates will be stored inside templates directory, so create a templates directory where you have your main.go file and have that file as below 

index.tmpl


<html>
<h1>
{{ .title }}
</h1>
<body>
{{ range .URLs}}
{{.Name}}
{{.Url}}
{{end}}
</body>
</html>

Hope it helps.

Thank you.

0 comments:

Post a Comment