How can I use division in a golang template. I need to divide Id
by 2.
For example
{{if .Id/2}}
HEY, I CAN DO IT!
{{else}}
WHY???
{{end}}
The package text/template
(and subsequently html/template
) can provide the functionality by defining division as a function using Template.Funcs
:
func (t *Template) Funcs(funcMap FuncMap) *Template
In your case, a FuncMap
with a divide function could look something like this:
fm := template.FuncMap{"divide": func(a, b int) int {
return a / b
}}
Full example (but without me trying to understand what you mean with if a/2
):
package main
import (
"os"
"text/template"
)
func main() {
fm := template.FuncMap{"divide": func(a, b int) int {
return a / b
}}
tmplTxt := `{{divide . 2}}`
// Create a template, add the function map, and parse the text.
tmpl, err := template.New("foo").Funcs(fm).Parse(tmplTxt)
if err != nil {
panic(err)
}
// Run the template to verify the output.
err = tmpl.Execute(os.Stdout, 10)
if err != nil {
panic(err)
}
}
Output:
5
Playground: http://play.golang.org/p/VOhTYbdj6P
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With