我在go中有一个非常简单的markdown应用程序,效果很好,但我真的很难排序索引帖子在页面上的顺序,我希望在文件中有一个整洁的方法来做到这一点。感谢您的帮助。
html是
<section>
{{range .}}
<a href="/{{.File}}"><h2 class="h2_home">{{.Title}} ({{.Date}})</h2></a>
<p>{{.Summary}}</p>
{{end}}
</section>索引页的go内容如下
func getPosts() []Post {
a := []Post{}
files, _ := filepath.Glob("posts/*")
for _, f := range files {
file := strings.Replace(f, "posts/", "", -1)
file = strings.Replace(file, ".md", "", -1)
fileread, _ := ioutil.ReadFile(f)
lines := strings.Split(string(fileread), "\n")
title := string(lines[0])
date := string(lines[1])
summary := string(lines[2])
body := strings.Join(lines[3:len(lines)], "\n")
htmlBody := template.HTML(blackfriday.MarkdownCommon([]byte(body)))
a = append(a, Post{title, date, summary, htmlBody, file, nil})
}
return a
}我已经有一段时间没有看到它了,因为它只是工作,但我真的想把一些东西放到文件中,以支持排序。.md文件已格式化
Hello Go lang markdown blog generator!
12th Jan 2015
This is a basic start to my own hosted go lang markdown static blog/ web generator.
### Here I am...
This entry is a no whistles Hello ... etc发布于 2017-11-01 01:14:56
请参阅排序包中的sort.Slice。这是一个用法的example。
对于您的特定问题,您有一个切片a []Post,因此只需对其调用sort.Slice,如下所示:
sort.Slice(a, func(i, j int) bool { return a[i].title < a[j].title })这只是根据标题对切片a的所有成员进行排序(假设您可以访问此包中Post的这个私有字段,如果不能,则需要添加一个函数)。
如果你这样做,你的帖子将按标题排序(或任何其他你想要的标准,也许你可以让用户选择标题或日期?)。你不需要调整你的markdown文件。
如果你想按日期排序,显然你的帖子应该先用时间包解析日期,这样你就有了真正的日期,而不仅仅是一个字符串。
所以就像这样(假设time.Time在邮报上):
// parse dates
date,err := time.Parse("2nd Jan 2006",string(lines[1]))
if err != nil {
// deal with it
}
// later, sort the slice
sort.Slice(a, func(i, j int) bool { return a[i].date.Before(a[j].date)})https://stackoverflow.com/questions/47040938
复制相似问题