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

标签 templates go

目前我正在使用 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/

相关文章:

javascript - 下划线/微模板替换换行符 - 奇怪的行为

c++方法根据字符串返回不同的类型

go - 如何检查一个包直接依赖/间接依赖另一个包?

go - 如何在 GO 中获取总内存/RAM?

c++ - 为什么模板参数失去常量性?

c++ - 如何访问其他模板类实例的私有(private)成员?

interface - 模板不会将接口(interface)类型的字段评估为基础类型

go - Bazel go_binary c-共享链接模式 : Where is the header?

go - 双 channel 死锁

c++ - C++模板-矩阵类