范围从时间到按年打印漂亮

Currently I'm printing post archive dates like so with https://play.golang.org/p/P1-sAo5Qy8:

Though I think it's nicer to print by year:

2009

2005

How would I range reverse chronically over the Posts PostDate, to print the grouping that I want? Can it be done all in the template?

Implement the sort.Interface on your Posts struct, then sort it in reverse order.

type Posts struct {
    Posts []Post
}

func (p Posts) Len() int {
    return len(p.Posts)
}

func (p Posts) Less(i, j int) bool {
    return p.Posts[i].PostDate.Before(p.Posts[j].PostDate)
}

func (p Posts) Swap(i, j int) {
    p.Posts[i], p.Posts[j] = p.Posts[j], p.Posts[i]
}

and

posts := Posts{p}
sort.Sort(sort.Reverse(posts))

That will give you the posts in the sequence you want them.

Next you'll have to implement a func using a closure so you can check if the current year is the same as the one for the last post to get the grouping by year. If yes output just the post, otherwise output a header with the year followed by the post.

currentYear := "1900"
funcMap := template.FuncMap{
    "newYear": func(t string) bool {
        if t == currentYear {
            return false
        } else {
            currentYear = t
            return true
        }
    },
}

and to use it:

{{ range . }}{{ if newYear (.PostDate.Format "2006") }}<li><h1>{{ .PostDate.Format "2006" }}</h1></li>{{ end }}

See a working example on the Playground.