gpt4 book ai didi

templates - 通过时间范围到按年份 pretty-print

转载 作者:数据小太阳 更新时间:2023-10-29 03:06:59 24 4
gpt4 key购买 nike

目前我正在使用 https://play.golang.org/p/P1-sAo5Qy8 像这样打印存档日期:

虽然我认为按年份打印更好:

2009

2005

我如何在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com