Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 292
Dany Avatar asked Mar 13 '16 06:03

Dany


1 Answers

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

like image 120
Aruna Herath Avatar answered Sep 23 '22 07:09

Aruna Herath