How to know if a range is empty?
Asked Answered
D

1

5

How can I conditionally display something else if my range is empty?

{{range .Users}}
...
{{end}}

If the range is empty, I want to display a different block of HTML.

Dunsinane answered 28/5, 2016 at 22:59 Comment(0)
M
8

Use {{range pipeline}} T1 {{else}} T0 {{end}}:

{{range pipeline}} T1 {{else}} T0 {{end}}
        The value of the pipeline must be an array, slice, map, or channel.
        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.

Example:

{{range .Users}}
...
{{else}}
<p>No users</p>
{{end}}
Massacre answered 28/5, 2016 at 23:0 Comment(2)
How could I just check if the .Users count is greater than 0? I don't want it to loop.Dunsinane
I agree with @Dunsinane . What does one do when rendering a table? One needs to know if there are a non-zero number of items before deciding whether to output the table's <th> tags etc. Ranging on the <td> - it's already too late.Haematoxylon

© 2022 - 2024 — McMap. All rights reserved.