Golang Templates folder ParseGlog tutorial# 4
Golang Templates folder ParseGlog tutorial# 4
We have create 3 html files and 3 routes
- index page
- help page
- contact page
How to serve HTML templates folder ?
tmpl, _ := template.ParseGlob("templates/*.html")
How to execute templates from templates folder?
tmpl.ExecuteTemplate(w, "help.html", nil)
or
tmpl.ExecuteTemplate(w, "help.html", "data")
<div>
<div>package main</div>
<div>import (</div>
<div> "html/template"</div>
<div> "net/http"</div>
<div>)</div>
<div>func main() {</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 passed to index page")</div>
<div> })</div>
<div> http.HandleFunc("/contact", func(w http.ResponseWriter, r *http.Request) {</div>
<div> tmpl.ExecuteTemplate(w, "contact.html", "data passed to contact Page")</div>
<div> })</div>
<div> http.HandleFunc("/help", func(w http.ResponseWriter, r *http.Request) {</div>
<div> tmpl.ExecuteTemplate(w, "help.html", "data passed to help Page")</div>
<div> })</div>
<div> http.ListenAndServe(":8080", nil)</div>
<div>}</div>
</div>
Index html file content
<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> INDEX HTML PAGE</div>
<div> <h1>INDEX HTML PAGE</h1></div>
<div> <h2>INDEX HTML PAGE</h2></div>
<div> <h3>INDEX HTML PAGE</h3></div>
<div> <h4>{{.}}</h4></div>
<div></body></div>
<div></html></div>
</div>
Help html file content
<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 HTML</title></div>
<div></head></div>
<div><body></div>
<div> HELP PAGE</div>
<div> <h1>HELP PAGE</h1></div>
<div> <h2>HELP PAGE</h2></div>
<div> <h3>HELP PAGE</h3></div>
<div> <h4>{{.}}</h4></div>
<div></body></div>
<div></html></div>
</div>
Contact html file content
<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 Contact HTML</title></div>
<div></head></div>
<div><body></div>
<div> Contact PAGE</div>
<div> <h1>Contact PAGE</h1></div>
<div> <h2>Contact PAGE</h2></div>
<div> <h3>Contact PAGE</h3></div>
<div> <h4>{{.}}</h4></div>
<div></body></div>
<div></html></div>
</div>