Welcome to our deep dive into Go Template Parsing! This lesson is designed for both beginners and intermediates, so let's get started. 🚀
In Go, template parsing is a feature that allows you to define and render HTML templates using Go functions. It's a powerful tool that helps in creating dynamic web pages, making your Go applications more flexible and user-friendly.
To use Go Template Parsing, first, you need to install the html/template package. If it's not installed, run:
go get -u golang.org/x/text/templateLet's create a simple template file named example.tmpl:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ .Title }}</title>
</head>
<body>
<h1>{{ .Message }}</h1>
</body>
</html>In the template, {{ .Title }} and {{ .Message }} are placeholders for data we'll pass later.
Now, let's create a Go program to render this template with data:
package main
import (
"html/template"
"os"
)
func main() {
// Parse the template
t := template.Must(template.ParseFiles("example.tmpl"))
// Prepare the data
data := struct {
Title string
Message string
}{
Title: "Go Template Parsing Example",
Message: "Welcome to Go Template Parsing!",
}
// Execute the template with data and write the result to stdout
if err := t.Execute(os.Stdout, data); err != nil {
panic(err)
}
}When you run the Go program, it renders the HTML template using the provided data and writes the output to the console.
Templates support custom functions and pipes for more complex manipulations of data.
{{ uppercase .Message }}In the Go code, you can define the function:
func (t *template.Template) uppercase(data interface{}) template.HTML {
return template.HTML(strings.ToUpper(data.(string)))
}Iterate through lists or slices in templates:
<ul>
{{ range .Items }}
<li>{{ . }}</li>
{{ end }}
</ul>In Go, you can pass the data:
data := struct {
Items []string
}{
Items: []string{"Go", "Rocks", "Templates"},
}What is the purpose of Go Template Parsing?
With these basics covered, you can start creating powerful, dynamic web applications using Go Template Parsing. Happy coding! 🎉