Welcome to our deep dive into Go's powerful html/template package! This tutorial is designed to help you understand how to create dynamic web pages using Go. By the end of this lesson, you'll be able to generate HTML content with ease. 📝 Note: This package comes built-in with Go, so you don't need to install anything extra!
In the context of Go, templates are a way to separate the HTML structure from the Go code. They serve as reusable blueprints for generating dynamic HTML pages.
Using templates simplifies the process of creating and maintaining HTML content. It allows you to write HTML in a format that's easy for developers to read and update, while keeping the logic and the structure separate.
Let's start by creating a simple template.
package main
import (
"html/template"
"fmt"
)
func main() {
tmpl := template.Must(template.New("example").Parse(`
<html>
<head>
<title>Go Template Example</title>
</head>
<body>
<h1>Hello, {{.}}!</h1>
</body>
</html>
`))
tmpl.Execute(os.Stdout, "World")
}In this example, we create a new template called "example" and execute it with the string "World" as the data. The {{.}} inside the template represents the data that we pass to it.
You can pass complex data structures, like maps and slices, to your templates as well.
type Person struct {
Name string
Age int
}
func main() {
// Create a new Person
p := Person{"John", 25}
tmpl := template.Must(template.New("person").Parse(`
<html>
<head>
<title>Person</title>
</head>
<body>
<h1>Name: {{.Name}}</h1>
<h2>Age: {{.Age}}</h2>
</body>
</html>
`))
tmpl.Execute(os.Stdout, p)
}In this example, we create a new Person data structure and pass it to the template.
Templates also support simple Go functions for complex operations.
func fullName(name, lastName string) string {
return name + " " + lastName
}
func main() {
tmpl := template.Must(template.New("person").Parse(`
<html>
<head>
<title>Person</title>
</head>
<body>
<h1>Full Name: {{fullName .Name "Doe"}}</h1>
</body>
</html>
`))
tmpl.Execute(os.Stdout, struct {
Name string
}{"John"})
}In this example, we define a function fullName and use it inside the template to concatenate two strings.
What does the {{.}} placeholder in a Go template represent?
In this lesson, you learned the basics of Go's html/template package, from understanding what templates are, why they're useful, to creating and executing templates with data and functions. Happy coding! 🎉