package main import ( "os" "text/template" ) func main() { tmpl, _ := template.New("foo").Parse("Hello {{.}}!") err := tmpl.Execute(os.Stdout, "world") if err != nil { panic(err) } }
package main import ( "os" "text/template" ) type Person struct { Name string Age int Address string } func main() { tmpl, _ := template.New("foo").Parse("{{.Name}} ({{.Age}}) lives at {{.Address}}.") p := Person{ Name: "John Doe", Age: 30, Address: "123 Main St.", } err := tmpl.Execute(os.Stdout, p) if err != nil { panic(err) } }This code creates a structured data template that uses data from a Person struct. The {{.FieldName}} placeholder is used to indicate where each field should be inserted into the template. The Execute method is called with a Person struct as the data parameter. The resulting output is "John Doe (30) lives at 123 Main St.". In conclusion, the text.template package is a powerful tool for creating dynamic templates and rendering them with data in Go. It's a part of the standard libraries in Go and can be used in any Go program without any additional packages or libraries.