package main import ( "fmt" "html/template" "os" ) func main() { type Person struct { Name string Age int } tmpl := template.New("test") tmpl, err := tmpl.Parse("{{.Name}} is {{.Age}} years old.") if err != nil { panic(err) } p := Person{Name: "John Doe", Age: 35} err = tmpl.Execute(os.Stdout, p) if err != nil { panic(err) } }
package main import ( "fmt" "html/template" "net/http" ) func handler(w http.ResponseWriter, r *http.Request) { tmpl := template.Must(template.ParseFiles("index.html")) data := struct { Title string Body string }{ Title: "Example Title", Body: "Example Body", } err := tmpl.Execute(w, data) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } } func main() { http.HandleFunc("/", handler) fmt.Println("Listening on port 8080...") err := http.ListenAndServe(":8080", nil) if err != nil { panic(err) } }
package main import ( "fmt" "html/template" "os" ) func main() { type Person struct { Name string Age int } tmpl := template.New("test") tmpl, err := tmpl.Parse("{{define `T`}}{{.Name}} is {{.Age}} years old.{{end}}") if err != nil { panic(err) } p := Person{Name: "John Doe", Age: 35} err = tmpl.ExecuteTemplate(os.Stdout, "T", p) if err != nil { panic(err) } }This example is similar to Example 1, however, the `ExecuteTemplate` method is used to execute a named template within a given data structure. In this case, the `T` template is defined within the source file using the `define` keyword. The package used here is `html/template`.