Golang Templates folder ParseGlog tutorial# 4

Golang Templates folder ParseGlog tutorial# 4

We have create 3 html files and 3 routes

  1. index page
  2. help page
  3. 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")

 


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

Index html file content


<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>
    INDEX HTML PAGE
    <h1>INDEX HTML PAGE</h1>
    <h2>INDEX HTML PAGE</h2>
    <h3>INDEX HTML PAGE</h3>
    <h4>{{.}}</h4>
</body>
</html>

Help html file content


<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 HTML</title>
</head>
<body>
    HELP PAGE
    <h1>HELP PAGE</h1>
    <h2>HELP PAGE</h2>
    <h3>HELP PAGE</h3>
    <h4>{{.}}</h4>
</body>
</html>

Contact html file content


<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 Contact HTML</title>
</head>
<body>
    Contact PAGE
    <h1>Contact PAGE</h1>
    <h2>Contact PAGE</h2>
    <h3>Contact PAGE</h3>
    <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: