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?

2 Answers 2

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)
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)
}
3
  • Is there a reason for using int64 and strconv? 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.
    – Tim Abell
    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?
    – VonC
    Feb 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.
    – Tim Abell
    Feb 23, 2018 at 9:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.