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
Advertisement
Something interesting
Tutorials
+18.5k Golang : Aligning strings to right, left and center with fill example
+17.9k Golang : How to make a file read only and set it to writable again?
+55.3k Golang : Unmarshal JSON from http response
+5.8k Unix/Linux : How to test user agents blocked successfully ?
+20.7k Golang : Read directory content with os.Open
+9.9k Golang : Sort and reverse sort a slice of integers
+11.4k Golang : Delay or limit HTTP requests example
+5.6k Golang : Detect words using using consecutive letters in a given string
+17.5k Golang : Linked list example
+19.1k Mac OSX : Homebrew and Golang
+32.5k Golang : Copy directory - including sub-directories and files
+5.4k Golang *File points to a file or directory ?