Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use division in a golang template?

Tags:

go

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}}
like image 953
cclsazob Avatar asked Apr 14 '15 11:04

cclsazob


1 Answers

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

like image 160
ANisus Avatar answered Nov 10 '22 06:11

ANisus