Golang Passing/insert data to templates tutorial # 5

Golang Passing/insert data to templates tutorial # 5

In this tutorial we are going to pass data to html files/templates.

How to pass data to frontend ?

data is the variable we going to pass to frontend.

tmpl.ExecuteTemplate(w, "index.html", data)

Why we used {{.}} in html file?

It is used to fetch data from backend.

Golang file


package main
import (
    "html/template"
    "net/http"
)
func main() {
    data := "data passed to index page"
    tmpl, _ := template.ParseGlob("templates/*.html")
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        tmpl.ExecuteTemplate(w, "index.html", data)
    })
    http.ListenAndServe(":8080", nil)
}

Index html file template


<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>GOLANG INDEX HTML</title>
</head>
<body>
    <h1>INDEX HTML PAGE</h1>
    <h4>{{.}}</h4>
</body>
</html>

Tony BB
 

TonyBB is a Coach , marketer, hypnotist and a founder of RSKVF Production who specializes in providing simple, affordable, and easy to use solutions for Life.

Click Here to Leave a Comment Below 0 comments

Leave a Reply: