1

I want to call a FuncMap in a template together with an if, something like:

{{if lt myFunc .templateVariable condition}} <span class="foo"> {{.templateVar}}</span> {{else}} {{.templateVar}} {{end}}

Looking at the docs it shows this only:

{{if eq .A 1 2 3 }} equal {{else}} not equal {{end}}

Is this possible in Go?

jwesonga
  • 4,249
  • 16
  • 56
  • 83
  • The following has good examples of the two approaches you could use: http://stackoverflow.com/questions/23466497/how-to-truncate-a-string-in-a-golang-template – miltonb May 08 '14 at 20:47

2 Answers2

3

Are you looking for something like this?

func main() {

    funcMap := template.FuncMap{
        "calculate": func(i int) int { return 42 },
    }

    tmpl := `{{$check := eq (calculate 1) 42}}{{if $check}}Correct answer{{end}}{{if not $check}}Wrong answer{{end}}`

    t, _ := template.New("template").Funcs(funcMap).Parse(tmpl)
    t.Execute(os.Stdout, "x")

}

Play

Sebastian
  • 16,813
  • 4
  • 49
  • 56
  • thanks!! that's exactly what I needed, though I tweaked mine to return a bool http://play.golang.org/p/jpsXdtZfB3 – jwesonga May 08 '14 at 21:29
0

Sounds like you should define your own function outside of the template, which accepts the required data and returns a int/bool so in the template you can keep the logic as simple as possibleL It would be something like this in your Go code:

 func (p *templateData) myFunc(templateVar Type, condition Type)  int {
     // logic
     return 0
 }

Within your template:

 {{if lt myFunc .templateVariable }} ...
miltonb
  • 6,905
  • 8
  • 45
  • 55