我知道在go模板中我可以调用以add表达式命名的函数,例如1 + 1。但是如何为表达式命名函数2 - 1呢?
go
add
1 + 1
2 - 1
您总是可以定义这样的功能:
package main import ( "html/template" "net/http" "strconv" ) var funcMap = template.FuncMap{ "minus": minus, } const tmpl = ` <html><body> <div> <span>{{minus 1 2}}</span> </div> </body></html>` var tmplGet = template.Must(template.New("").Funcs(funcMap).Parse(tmpl)) func minus(a, b int64) string { return strconv.FormatInt(a-b, 10) } func getPageHandler(w http.ResponseWriter, r *http.Request) { if err := tmplGet.Execute(w, nil); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } } func main() { http.HandleFunc("/", getPageHandler) http.ListenAndServe(":8080", nil) }