Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if a range is empty?

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.

like image 755
Blankman Avatar asked Mar 12 '23 04:03

Blankman


1 Answers

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}}
like image 83
Tim Cooper Avatar answered Mar 24 '23 07:03

Tim Cooper