Substraction in golang "text/template"

Hi, i can’t do subtractions in if condition i’ts normal ?

My code :

{{$len := len .Members}}
{{if gt $len 1}}
  {{range $key2, $value2 := .Members}}
    {{$value2}}
    {{if lt $key2 $len-1}}
       | 
    {{end}}
  {{end}}
{{end}}

Any ideas ?
Thanks

Usually you can modify your template to make expressions unnecessary:

{{range $key2, $value2 := .Members}}
    {{- if gt $key2 0}}|{{end}}{{$value2}}
{{- end}}

However, to answer your question about subtraction: You’re correct that you cannot use infix operators like +, -, etc. in Go templates. That’s why the check for less than is lt left right. You could write your own sub function like this:

func sub(a, b int) int { return a - b}

// and then wherever you're initializing your template, register your sub function like this:

tmpl := template.New("")/* ... */.Funcs(template.FuncMap{"sub": sub})/* ... */.Execute(...)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.