How to compare the length of a list in html/template in golang?

47,211

Solution 1

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

Solution 2

A shorter version

{{ if eq (len .SearchData) 0 }}
    Sorry. No matching results found
{{ end }}

Solution 3

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 }}
Share:
47,211

Related videos on Youtube

Dany
Author by

Dany

Graduate Student at The University of Texas at Dallas | Coder | Former Employee of Verizon and Accenture About Dinesh Code Repository

Updated on January 24, 2020

Comments

  • Dany
    Dany over 4 years

    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
    Dany about 8 years
    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].
  • Aruna Herath
    Aruna Herath about 8 years
    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?
  • Dany
    Dany about 8 years
    Yeah. I am passing the indented values because {{if not .SearchData}} works as expected. I tested with empty list and list with some values
  • c0degeas
    c0degeas over 5 years
    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.