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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35967109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 19:04:24  来源:igfitidea点击:

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

htmlgoequalsgo-html-template

提问by Dany

I am trying to compare the length of a list in golang html/template. But it is loading forever in html.

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

{{ $length := len .SearchData }} {{ if eq $length "0" }}
    Sorry. No matching results found
{{ end }}

Could anyone help me with this?

有人可以帮我解决这个问题吗?

回答by Aruna Herath

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.

{{if pipeline}} T1 {{end}}:如果管道的值为空,则不产生输出;否则,执行T1。空值是 false、0、任何 nil 指针或接口值,以及任何长度为零的数组、切片、映射或字符串。点不受影响。

So if you want to check if the .SearchDataslice/array/map is empty just use,

因此,如果您想检查.SearchData切片/数组/映射是否为空,请使用,

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

Even your code runs fine if string "0"is replaced by int 0

如果 string"0"被 int 替换,即使你的代码也能正常运行0

{{ $length := len .SearchData }} {{ if eq $length 0 }}
    Sorry. No matching results found
{{ end }}

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

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

回答by emicklei

A shorter version

较短的版本

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

回答by Oleg Neumyvakin

There is {{ else }}for {{ range }}Works well for maps as well https://play.golang.org/p/7xJ1LXL2u09:

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

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