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
+7.7k Javascript : Push notifications to browser with Push.js
+25.6k Golang : Generate MD5 checksum of a file
+10.1k Golang : Read file and convert content to string
+14.6k Golang : How to pass map to html template and access the map's elements
+21.2k Golang : For loop continue,break and range
+8.8k Golang : Executing and evaluating nested loop in html template
+7.5k Golang : Handling Yes No Quit query input
+7.1k Golang : How to call function inside template with template.FuncMap
+10.6k Golang : Select region of interest with mouse click and crop from image
+10.3k Golang : Use regular expression to get all upper case or lower case characters example
+17.1k Golang : XML to JSON example