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
<div> <div>package main</div> <div>import (</div> <div> "html/template"</div> <div> "net/http"</div> <div>)</div> <div>func main() {</div> <div> data := "data passed to index page"</div> <div> tmpl, _ := template.ParseGlob("templates/*.html")</div> <div> http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {</div> <div> tmpl.ExecuteTemplate(w, "index.html", data)</div> <div> })</div> <div> http.ListenAndServe(":8080", nil)</div> <div>}</div> </div>
Index html file template
<div> <div><html lang="en"></div> <div><head></div> <div> <meta charset="UTF-8"></div> <div> <meta http-equiv="X-UA-Compatible" content="IE=edge"></div> <div> <meta name="viewport" content="width=device-width, initial-scale=1.0"></div> <div> <title>GOLANG INDEX HTML</title></div> <div></head></div> <div><body></div> <div> <h1>INDEX HTML PAGE</h1></div> <div> <h4>{{.}}</h4></div> <div></body></div> <div></html></div> </div>