Dan*_*any 21 html equals go go-html-template
我试图比较golang html/template中列表的长度.但它在html中永远加载.
{{ $length := len .SearchData }} {{ if eq $length "0" }}
Sorry. No matching results found
{{ end }}
Run Code Online (Sandbox Code Playgroud)
任何人都可以帮我这个吗?
Aru*_*ath 44
从文档,
{{if pipeline}} T1 {{end}}:如果管道的值为空,则不生成输出; 否则,执行T1.空值为false,0,任何nil指针或接口值,以及长度为零的任何数组,切片,映射或字符串.点不受影响.
所以,如果你想检查.SearchData
切片/数组/地图是否为空,只需使用,
{{if not .SearchData}} Nothing to show {{end}}
Run Code Online (Sandbox Code Playgroud)
如果string "0"
被int替换,即使你的代码运行也很好0
{{ $length := len .SearchData }} {{ if eq $length 0 }}
Sorry. No matching results found
{{ end }}
Run Code Online (Sandbox Code Playgroud)
http://play.golang.org/p/Q44qyRbKRB
小智 36
更短的版本
{{ if eq (len .SearchData) 0 }}
Sorry. No matching results found
{{ end }}
Run Code Online (Sandbox Code Playgroud)
还有{{ else }}
适用{{ range }}
于地图的https://play.golang.org/p/7xJ1LXL2u09:
{{range $item := . }}
<span>{{ $item }}</span>
{{ else }}
<span>Sorry no rows here</span>
{{ end }}
Run Code Online (Sandbox Code Playgroud)