如何比较golang中html/template中列表的长度?

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

我正在尝试比较 golang 中列表的长度 html/template。但它在 html.

中永远加载
{{ $length := len .SearchData }} {{ if eq $length "0" }}
    Sorry. No matching results found
{{ end }}

谁能帮我解决这个问题?

来自文档,

{{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.

所以如果你想检查 .SearchData slice/array/map 是否为空,只需使用

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

如果将字符串 "0" 替换为 int 0

,即使您的代码运行良好
{{ $length := len .SearchData }} {{ if eq $length 0 }}
    Sorry. No matching results found
{{ end }}

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

更短的版本

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

{{ else }} {{ range }} 也适用于地图 https://play.golang.org/p/7xJ1LXL2u09:

{{range $item := . }}    
    <span>{{ $item }}</span>
{{ else }}
    <span>Sorry no rows here</span>
{{ end }}