package main import ( "os" "text/template" ) func main() { tmpl, _ := template.New("hello").Parse("Hello, {{.Name}}!") data := struct{ Name string }{ "World" } tmpl.Execute(os.Stdout, data) }
package main import ( "os" "text/template" ) func main() { tmpl, _ := template.New("list").Parse(` {{range .Items}} {{if eq .Type "fruit"}} {{.Name}} - {{.Color}} {{else if eq .Type "vegetable"}} {{.Name}} - {{.Season}} {{end}} {{end}} `) data := struct{ Items []Item }{ { Type: "fruit", Name: "Apple", Color: "Red", }, { Type: "vegetable", Name: "Carrot", Season: "Fall", }, { Type: "fruit", Name: "Banana", Color: "Yellow", }, } tmpl.Execute(os.Stdout, data) } type Item struct { Type string Name string Color string Season string }In this example, we define a more complicated template that includes a loop over an array of items. For each item, we use an `if` statement to check its `Type` field and output different properties based on that value. We then define an array of `Item` structs and pass that data to the template. This results in a list of items being output with different properties based on their type. In conclusion, the Go text/template package is a versatile library that can handle a wide range of text-based templating needs. Its simple syntax and powerful features make it a popular choice for generating dynamic content in Go applications.