Welcome to our deep dive into Go Templates! In this comprehensive guide, we'll explore how to harness the power of templates to generate dynamic content in your Go programs. Let's get started!
Go Templates are a powerful feature that allows you to define and manipulate text templates to generate dynamic output. They're useful for tasks like generating HTML, SQL queries, configuration files, and more!
Templates are defined using Go's template package. Here's a simple example of a template that generates a greeting:
package main
import (
"text/template"
"fmt"
)
func main() {
tmpl, err := template.New("greeting").Parse(`
Hello, {{.Name}}!
Welcome to Go Templates!
`)
if err != nil {
fmt.Println(err)
return
}
data := struct {
Name string
}{
Name: "World",
}
err = tmpl.Execute(os.Stdout, data)
if err != nil {
fmt.Println(err)
}
}In the example above, we define a simple template greeting and use it to generate a greeting for "World."
In the template, {{.Name}} is a variable that takes the value from the corresponding field in the data structure. Go Templates also support built-in functions, like len and text/template functions, like html and json.
Go Templates support basic control structures like if, else, and loops. You can use them to conditionally generate content based on your data.
The pipe operator (|) is used to chain functions. For example, to HTML-escape the output, you can use {{ .Content | html }}.
Let's create a more complex example, where we generate an HTML document with a list of items.
package main
import (
"text/template"
"fmt"
)
type Item struct {
Name string
Desc string
}
func main() {
items := []Item{
{"Apples", "Fruits with red or yellow skin"},
{"Bananas", "Curved, yellow fruit with soft flesh"},
}
tmpl, err := template.New("items").Parse(`
<ul>
{{range .}}
<li>{{.Name}} - {{.Desc}}</li>
{{end}}
</ul>
`)
if err != nil {
fmt.Println(err)
return
}
err = tmpl.Execute(os.Stdout, items)
if err != nil {
fmt.Println(err)
}
}This example generates an HTML unordered list with the items from the items slice.
What is the purpose of Go Templates?
Now that you've learned the basics of Go Templates, it's time to dive deeper and explore their advanced features! Happy coding! 🚀