目前我正在使用 https://play.golang.org/p/P1-sAo5Qy8 像这样打印存档日期:
- 2009 年 11 月 10 日» Something happened in 2009
- 2005 年 11 月 10 日» Something happened 10 years ago
- 2009 年 6 月 10 日» Summer of 2009
虽然我认为按年份打印更好:
2009
- 2009 年 11 月 10 日» Something happened in 2009
- 2009 年 6 月 10 日» Summer of 2009
2005
- 2005 年 11 月 10 日» Something happened 10 years ago
我如何在 Posts PostDate 上长期反向排列,以打印我想要的分组?能不能都在模板里搞定?
最佳答案
实现sort.Interface在您的 Posts
结构上,然后以相反的顺序对其进行排序。
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]
}
和
posts := Posts{p}
sort.Sort(sort.Reverse(posts))
这将按照您想要的顺序为您提供帖子。
接下来,您必须使用闭包实现一个函数,这样您就可以检查当前年份是否与上一篇文章的年份相同,以便按年份进行分组。如果是,则仅输出帖子,否则输出带有年份的标题,后跟帖子。
currentYear := "1900"
funcMap := template.FuncMap{
"newYear": func(t string) bool {
if t == currentYear {
return false
} else {
currentYear = t
return true
}
},
}
并使用它:
{{ range . }}{{ if newYear (.PostDate.Format "2006") }}<li><h1>{{ .PostDate.Format "2006" }}</h1></li>{{ end }}
查看工作示例 on the Playground .
关于templates - 通过时间范围到按年份 pretty-print ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30284533/