I'm trying to use a variable declared outside a Go template range loop to see if the previous post occurred on the same day as the current post. Here's a simplified example.
Where .Posts
is an array of post structs that each have a .Content
and a .Date
.
{{ $prevDate := "" }}
{{ range $post := .Posts }}
{{ if ne $prevDate $post.Date }}
<div class="post-date">Posts dated: {{ $post.Date }}</div>
{{ end }}
<div class="post-content">{{ $post.Content }}</div>
{{ $prevDate := $post.Date }}
{{ end }}
The problem is that $prevDate
seems to be reset to ""
at the start of each iteration of the loop.
Can anyone help me understand why the value of $prevDate
is reset on each iteration and perhaps suggest a way to accomplish what I'm trying to do here?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…