data perhitungan dalam template go
package main
import (
"net/http"
"text/template"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
html := `
<h1> Total days: {{ len .days }}</h1>
{{ with $days := "Days list" }}
<h1> {{ $days }} </h1>
{{ end }}
<ul>
{{ range $index, $day := .days }}
<li> {{ inc $index }}. {{ $day }} </li>
{{ end }}
</ul>
<h1> Calculate: {{ add 4 2 }} </h1>
`
data := map[string][]string{"days": []string{"senin", "selasa", "rabu"}}
tmpFunc := template.FuncMap{
"inc": func(i int) int {
return i + 1
},
"add": func(i int, j int) int {
return i + j
},
}
parse, err := template.New("index.html").Funcs(tmpFunc).Parse(html)
tmp := template.Must(parse, err)
tmp.Execute(w, data)
})
http.ListenAndServe(":3000", nil)
}
Restu Wahyu Saputra