I know that in go
templates I can call function named add
for expression like 1 + 1
. But how named function for expression like 2 - 1
?
2 Answers
There is no add
function included by default. You can however, easily write such functions yourself. For example:
tmpl := template.Must(template.New("").Funcs(template.FuncMap{
"minus": func(a, b int) int {
return a - b
},
}).Parse("{{ minus 5 2 }}"))
tmpl.Execute(os.Stdout, nil)
You could always define such a function:
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)
}
-
Is there a reason for using
int64
andstrconv
? The other answer stackoverflow.com/a/24838014/10245 doesn't and avoids a int/int64 conversion error for me. Thanks for the answer though, it was useful. Feb 23, 2018 at 2:18 -
@TimAbell 4 years later, I don't remember. Do you get an error with golang.org/pkg/strconv/#FormatInt?– VonCFeb 23, 2018 at 7:28
-
Lol I'm late to the party clearly. The error was converting the literal int in my template to an int64. I didn't look into it further. Feb 23, 2018 at 9:07