So, you’ve built a Go web server, but returning plain text just isn’t cutting it anymore? It’s time to level up and use HTML templates! Templates let you generate dynamic web pages without hardcoding everything.
Why Use HTML Templates in Go?
Instead of manually building HTML strings in Go (which is a nightmare), templates allow you to:
- Separate logic and presentation (keep your code clean!)
- Reuse HTML layouts (no more copy-pasting!)
- Pass dynamic data into pages (like user info, articles, etc.)
Go’s built-in html/template
package makes this super easy.
Creating Your First Template
Let’s start by creating a simple HTML file.
Example: Basic HTML Template (template.html
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ .Title }}</title>
</head>
<body>
<h1>{{ .Heading }}</h1>
<p>{{ .Message }}</p>
</body>
</html>
The {{ .Title }}
, {{ .Heading }}
, and {{ .Message }}
are placeholders that will be replaced dynamically.
Rendering the Template in Go
Now, let’s write some Go code to render this template.
Example: Rendering HTML with Data
package main
import (
"html/template"
"net/http"
)
type PageData struct {
Title string
Heading string
Message string
}
func handler(w http.ResponseWriter, r *http.Request) {
tmpl, _ := template.ParseFiles("template.html")
data := PageData{
Title: "Welcome to Go Templates!",
Heading: "Hello, Gophers!",
Message: "This page is powered by Go’s template engine.",
}
tmpl.Execute(w, data)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
Now, when you visit http://localhost:8080
, you’ll see a nicely rendered HTML page instead of boring plain text!
Using Template Functions
Want to manipulate data before displaying it? Go templates support functions!
Example: Uppercasing Text
<h1>{{ .Heading | upper }}</h1>
To use this, modify your Go code:
import "strings"
var funcMap = template.FuncMap{
"upper": strings.ToUpper,
}
tmpl := template.New("template.html").Funcs(funcMap)
tmpl, _ = tmpl.ParseFiles("template.html")
Boom! Now Hello, Gophers!
becomes HELLO, GOPHERS!
automatically.
Templates make Go web development cleaner and more efficient. Now, go build something awesome and give your web pages a glow-up!
0 Comments