如何检查我的结构的一部分是否在范围内为 0

How to check if part of my struct is 0 in range

这是我的模板文件的一部分:

{{range .CartList}}
{{.ID}}
{{.Name}}
{{.Description}}
{{end}}

CartList 是我的模板页面数据的一部分,它是 []model.Equipment

这是我的设备结构:

type Equipment struct {
    ID int
    Name string
    Description string
    ImgPath string
    Category string
    Availability bool
    Amount string
    Storage string
    Owner int
}

基本上我想检查 .ID 是否为 0,如果是这种情况,它应该显示如下消息:"No Articles in your Cart available"

到目前为止,它显示的是这样的空购物车 [0 false 0..

我也试过这个:

{{if .CartList}}
{{range .CartList}}
BODY
{{else}}
"Cart not Available"
{{end}}
{{end}}

{{if .CartList}} Body {{end}} 就是您要找的

您确定要检查 ID 是否为 0 吗?如果您想在 CartList 中没有任何项目时显示替代消息,您可以使用 range-else 语法。

{{range .CartList}}
{{.ID}}
{{.Name}}
{{.Description}}
{{else}}
No Articles in your Cart available
{{end}}

引用 documentation for text/template:

If the value of the pipeline has length zero, dot is unaffected and T0 is executed; otherwise, dot is set to the successive elements of the array, slice, or map and T1 is executed.

您不需要将它放在 if 中(就像您在 OP 中所做的那样)。如果您将 {{end}} 行之一移动到 {{else}}.

上方,您在 OP 的最后一个示例中所做的将起作用

如果您想要在 ID 为 0 时显示消息:

{{range .CartList}}
    {{if .ID}}
        {{.ID}}
        {{.Name}}
        {{.Description}}
    {{else}}
        No Articles in your Cart available
    {{end}}
{{end}}