duanliao6789 2017-10-31 17:11
浏览 68

GO Lang降价应用

I have a very simple markdown app in go which works great but I am really struggling to sort the order of the index posts on the page and would like a neat way in the file to do this. Any help appreciated.

html is

<section>
{{range .}}
<a href="/{{.File}}"><h2 class="h2_home">{{.Title}} ({{.Date}})</h2></a>
<p>{{.Summary}}</p>
{{end}}
 </section>

and the go stuff for the index page is as follows

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), "
")
    title := string(lines[0])
    date := string(lines[1])
    summary := string(lines[2])
    body := strings.Join(lines[3:len(lines)], "
")
    htmlBody := template.HTML(blackfriday.MarkdownCommon([]byte(body)))

    a = append(a, Post{title, date, summary, htmlBody, file, nil})
}
return a
}

Ive not looked at it for a while as it just works but I really want to put something into the file to support ordering. The .md file is formatted

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
  • 写回答

1条回答 默认 最新

  • duandu9260 2017-10-31 17:14
    关注

    See sort.Slice in the sort package. Here is an example of usage.

    For your particular problem, you have a slice a []Post, so just call sort.Slice on it like this:

    sort.Slice(a, func(i, j int) bool { return a[i].title < a[j].title })
    

    This is just sorting all members of the slice a based on their title (assuming you can access this private field of a Post in this package, if not you'd need to add a function).

    If you do that your slice a of posts will be sorted by title (or any other criteria you wish, perhaps you could give the user a choice of title or date?). You don't need to adjust your markdown files.

    If you want to sort on dates obviously your Post should parse the dates with the time package first so that you have real dates, not just a string.

    So something like this (assuming time.Time on the Post):

    // 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)})
    
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题