Golang html/template.Template.Execute function examples

package html/template

Execute applies a parsed template to the specified data object, writing the output to wr. If an error occurs executing the template or writing its output, execution stops, but partial results may already have been written to the output writer. A template may be executed safely in parallel.

Golang html/template.Template.Execute function usage examples

Example 1:

 package main

 import (
 "fmt"
 "html/template"
 "os"
 )

 var defaultTemplate string = `<!DOCTYPE html>
 <html lang="en">
 <head>
 <title>{{ .Title }}</title>
 </head>`

 func main() {

 t := template.New("HELLO")

 t.Parse(defaultTemplate)

 data := map[string]interface{}{
 "Title": "Hello World!", // replace {{ .Title }} with the string "Hello World!
 }

 t.Execute(os.Stdout, data) // output to screen 

 fmt.Println("\n\n")

 fmt.Println("Template name is : ", t.Name())

 }

Output :

 <!DOCTYPE html>
 <html lang="en">
  <head>
 <title>Hello World!</title>
  </head>

Template name is : HELLO

Example 2:

 //// web dashboard
 func webIndexHandler(w http.ResponseWriter, r *http.Request, Opts SweetOptions) {
  if r.URL.Path != "/" {
 http.NotFound(w, r)
 return
  }
  pageTemplate, err := Asset("tmpl/index.html")
  if err != nil {
 Opts.LogFatal(err)
  }
  t, err := template.New("name").Parse(string(pageTemplate))
  if err != nil {
 Opts.LogFatal(err)
  }
  hostname, err := os.Hostname()
  if err != nil {
 Opts.LogFatal(err)
  }
  reports := make(map[string]Report, 0)
  for _, device := range Opts.Devices {
 report, _ := getDeviceWebReport(device, Opts)
 reports[device.Hostname] = *report
  }
  data := map[string]interface{}{
 "Title": "Dashboard",
 "MyHostname": hostname,
 "Devices": reports,
 "Now": time.Now().Format("15:04:05 MST"),
  }
  err = t.Execute(w, data) // <--- HERE
  if err != nil {
 Opts.LogFatal(err)
  }
 }

References :

https://github.com/AppliedTrust/sweet/blob/master/webstatus.go

http://golang.org/pkg/html/template/#Template.Execute

Advertisement