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>package main</div>
<div>import (</div>
<div>    "html/template"</div>
<div>    "net/http"</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>

Index html file template

<div>&lt;html lang="en"&gt;</div>
<div>    &lt;meta charset="UTF-8"&gt;</div>
<div>    &lt;meta http-equiv="X-UA-Compatible" content="IE=edge"&gt;</div>
<div>    &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;</div>
<div>    &lt;title&gt;GOLANG INDEX HTML&lt;/title&gt;</div>
<div>    &lt;h1&gt;INDEX HTML PAGE&lt;/h1&gt;</div>
<div>    &lt;h4&gt;{{.}}&lt;/h4&gt;</div>
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: