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

血红的双手。 提交于 2019-12-03 08:32:02

问题


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?


回答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




回答2:


A shorter version

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



回答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 }}


来源:https://stackoverflow.com/questions/35967109/how-to-compare-the-length-of-a-list-in-html-template-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!