Introduction
Go's templating system allows you to create dynamic web pages by rendering data within HTML templates. In this guide, we'll explore Go templating, including the use of the `html/template` package, and provide sample code to demonstrate how to create dynamic web pages with Go.
The `html/template` Package
The `html/template` package is part of Go's standard library and provides a simple and secure way to generate HTML and other text-based formats. It supports the injection of dynamic data into templates using placeholders.
Basic Templating
Let's start with a simple example of using the `html/template` package to create a dynamic web page. In this example, we have a template that includes placeholders for dynamic content:
package main
import (
`html/template`
`os`
)
func main() {
tmpl, _ := template.New(`example`).Parse(`Hello, {{.}}!`)
tmpl.Execute(os.Stdout, `World`)
}
In this code, we create a template with a placeholder `{{.}}` and use `Execute` to render the template with the value `World.` The result is `Hello, World!`.
Passing Data to Templates
You can pass data to templates by defining a struct or a map and then using the data in the template. Here's an example of passing a struct to a template:
package main
import (
`html/template`
`os`
)
type Person struct {
Name string
}
func main() {
person := Person{Name: `Alice`}
tmpl, _ := template.New(`example`).Parse(`Hello, {{.Name}}!`)
tmpl.Execute(os.Stdout, person)
}
In this code, we create a `Person` struct, pass it to the template, and access the `Name` field within the template.
Looping and Conditional Logic
Go templates support looping and conditional logic. Here's an example of looping through a list of names and rendering them in an HTML list:
package main
import (
`html/template`
`os`
)
type Person struct {
Name string
}
func main() {
people := []Person{
{Name: `Alice`},
{Name: `Bob`},
{Name: `Charlie`},
}
tmpl, _ := template.New(`example`).Parse(`
<ul>
{{range .}}
<li>{{.Name}}</li>
{{end}}
</ul>
`)
tmpl.Execute(os.Stdout, people)
}
In this code, we define a slice of `Person` structs, use the `range` directive in the template to loop through the list, and render each name as an HTML list item.
Further Resources
To continue learning about Go templating, consider these resources:
- html/template Package Documentation - Official Go documentation for the `html/template` package.
- Go by Example - Templates - Practical examples of using templates in Go.
