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

huangapple go评论88阅读模式
英文:

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

问题

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

{{ $length := len .SearchData }} {{ if eq $length "0" }}
	抱歉,没有找到匹配的结果
{{ end }}

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

英文:

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

得分: 91

根据文档,

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

因此,如果你想检查 .SearchData 切片/数组/映射是否为空,只需使用以下代码:

{{if not .SearchData}} 没有要显示的内容 {{end}}

即使你的代码中用字符串 "0" 替换为整数 0,也可以正常运行:

{{ $length := len .SearchData }} {{ if eq $length 0 }}
    抱歉,没有找到匹配的结果
{{ end }}

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

英文:

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

得分: 72

一个更简短的版本

{{ if eq (len .SearchData) 0 }}
    抱歉,没有找到匹配的结果
{{ end }}
英文:

A shorter version

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

答案3

得分: 13

以下是翻译好的内容:

{{ else }}{{ range }} 中也适用于映射,示例代码如下:https://play.golang.org/p/7xJ1LXL2u09:

{{range $item := . }}    
    <span>{{ $item }}</span>
{{ else }}
    <span>抱歉,这里没有行</span>
{{ end }}
英文:

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

huangapple
  • 本文由 发表于 2016年3月13日 14:06:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/35967109.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定