11

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?

cnaize
  • 3,139
  • 5
  • 27
  • 45

2 Answers2

13

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)
tux21b
  • 90,183
  • 16
  • 117
  • 101
7

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)
}
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • Is there a reason for using `int64` and `strconv`? The other answer https://stackoverflow.com/a/24838014/10245 doesn't and avoids a int/int64 conversion error for me. Thanks for the answer though, it was useful. – Tim Abell Feb 23 '18 at 02:18
  • @TimAbell 4 years later, I don't remember. Do you get an error with https://golang.org/pkg/strconv/#FormatInt? – VonC Feb 23 '18 at 07: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. – Tim Abell Feb 23 '18 at 09:07