package main import ( "text/template" "os" ) func main() { // Template string tmplString := "Hello {{.Name}}! Your age is {{.Age}}.\n" // Parse template string tmpl, err := template.New("my-template").Parse(tmplString) if err != nil { panic(err) } // Data to execute template with data := map[string]interface{}{ "Name": "John", "Age": 30, } // Execute template with data err = tmpl.Execute(os.Stdout, data) if err != nil { panic(err) } }
package main import ( "text/template" "os" ) func main() { // Parse template file tmpl, err := template.ParseFiles("template.html") if err != nil { panic(err) } // Data to execute template with data := map[string]interface{}{ "Title": "Template Example", "Body": "This is an example of parsing a template file.", } // Execute template with data err = tmpl.Execute(os.Stdout, data) if err != nil { panic(err) } }This example parses a template file called "template.html" and executes it with data. The data contains a title and body string that will be used to replace placeholders in the template file. The result is printed to the console. Both examples use the go text/template package's Template.Parse() function to parse a template string or file, then execute it with specific data.