I’m trying to display a list of posts with the date split into a heading for year published and a sub-heading for date published. I want something like this:
2016
13 Feb –some post
10 Feb –some post
05 Feb –some post
2015
30 Dec –some post
20 Dec –some post
09 Dec –some post
…etc
So the main year heading is only generated when the year changes.
I’m presuming the way to do it is via storing the year as a scratch variable and then, on each loop through the range of posts, comparing the postdate year to the year stored in the scratch variable and only printing it to the page, if it’s different.
So far, I’ve come up with:
{{ range .Data.Pages }}
<!--compare post year to currentyear stored in scratch var -->
<!-- should fail on first loop as we've not stored anything in scratch var yet -->
{{ if eq (.Date.Format "2006") ($.Scratch.Get "currentyear")}}
<!-- post year and scratch var currentyear the same, do nada -->
{{else}}
<!-- post year and scratch var currentyear different so print year -->
{{ .Date.Format "2006" }}
<!-- store post year in scratch var currentyear -->
{{ $.Scratch.Set "currentyear" (.Date.Format "2006")}}
{{end}}
{{end}}
I’m getting the year printed every time, even if it’s not different from the previous post. So the comparison part is obviously failing. I suspect this may be owing to either:
- As
{{ .Date.Format "2006" }}
is parsing the date into a human readable form, I’m possibly not comparing like with like when I compare it to “2006” stored as a scratch var [string vs number?] - [As usual] I’ve got a glitch in my comparison syntax
Any suggestions?