ChristopherG1994
ChristopherG1994

Reputation: 9

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

This is a part of my template file:

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

CartList is part of my Template Page Data it's a []model.Equipment

This is my Equipment Struct:

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

Basically I want to check if .ID is 0 and if this is the case it should display a message like: "No Articles in your Cart available"

Until now it shows an empty cart like this [0 false 0..

I also tried this:

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

Upvotes: 0

Views: 42

Answers (2)

morganbaz
morganbaz

Reputation: 3117

Are you sure you need to check if ID is 0? If you want to show an alternative message when there are no items inside of CartList, you can use the range-else syntax.

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

Quoting the 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.

You don't need to place this inside an if (like you did in OP). What you did in the last example of the OP would work if you moved one of the {{end}} lines above the {{else}}.


If you want to show a message if ID is 0:

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

Upvotes: 1

CallMeLoki
CallMeLoki

Reputation: 1361

{{if .CartList}} Body {{end}} is what your'e looking for

Upvotes: 0

Related Questions