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
+5.7k Golang : Reverse by word
+11k Golang : How to parse plain email text and process email header?
+19.5k Golang : Clean up null characters from input data
+4.1k Golang : Convert lines of string into list for delete and insert operation
+31.2k Golang : How to check if a date is within certain range?
+28.2k Golang : Login(Authenticate) with Facebook example
+13.2k Golang : On enumeration
+25.5k PHP : Convert(cast) string to bigInt
+9.4k Golang : How to delete element(data) from map ?
+6k Golang : Get Alexa ranking data example
+6.4k Javascript : Push notifications to browser with Push.js
+9k Golang : Print how to use flag for your application example