54

I am trying to compare the length of a list in golang html/template. But it is loading forever in html.

{{ $length := len .SearchData }} {{ if eq $length "0" }}
    Sorry. No matching results found
{{ end }}

Could anyone help me with this?

Dany
  • 2,692
  • 7
  • 44
  • 67

3 Answers3

91

From documentation,

{{if pipeline}} T1 {{end}}: If the value of the pipeline is empty, no output is generated; otherwise, T1 is executed. The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. Dot is unaffected.

So if you want to check if the .SearchData slice/array/map is empty just use,

{{if not .SearchData}} Nothing to show {{end}}

Even your code runs fine if string "0" is replaced by int 0

{{ $length := len .SearchData }} {{ if eq $length 0 }}
    Sorry. No matching results found
{{ end }}

http://play.golang.org/p/Q44qyRbKRB

Aruna Herath
  • 6,241
  • 1
  • 40
  • 59
  • For some reasons `{{ $length := len .SearchData }} {{ if eq $length 0 }}` is not working in my html template. But `{{if not .SearchData}}` works. But in some scenarios I have to use `eq` with different values[to restrict the results]. – Dany Mar 13 '16 at 06:28
  • I understand your need to check for other values. I can't think of why it wouldn't work for you :( Must be something outside templates. Are you sure you are passing the intended value for `SearchData`? – Aruna Herath Mar 13 '16 at 06:34
  • Yeah. I am passing the indented values because `{{if not .SearchData}}` works as expected. I tested with `empty` list and list with some values – Dany Mar 13 '16 at 06:37
  • Be careful, in case the result is a number, it returns the total number of digits. Eg, if SearchData is "1234567890", the length will be 10, rather than 1. – c0degeas Oct 08 '18 at 10:47
  • What if "SearchData" is a template function instead, registered with "Funcs"? `{{if not SearchData }}` will throw error "wrong number of args for SearchData: want 1 got 0". A `{{with SearchData .}}` works, but if SearchData returns an empty array, the template in the "with" block is not even rendered so I can't test the array length there. – Eric Burel May 02 '23 at 07:45
72

A shorter version

{{ if eq (len .SearchData) 0 }}
    Sorry. No matching results found
{{ end }}
emicklei
  • 1,321
  • 11
  • 10
13

There is {{ else }} for {{ range }} Works well for maps as well https://play.golang.org/p/7xJ1LXL2u09:

{{range $item := . }}    
    <span>{{ $item }}</span>
{{ else }}
    <span>Sorry no rows here</span>
{{ end }}
Oleg Neumyvakin
  • 9,706
  • 3
  • 58
  • 62