HUGO

Sorting blog posts in descending order

I’m trying to figure out how to sort blog posts only on my index page

I can sort using

{{ range .Data.Pages.ByDate.Reverse }} {{.Title}}</br>  {{ end }}

and I can restrict to just posts using

{{ range where .Data.Pages "Section" "post" }} {{.Title}}</br>  {{ end }}

I need to combine them so I only include posts in reversed order (Most recent first), I guess i could use an inner if test but if I can achieve with a single function, it would be preferable.

Thanks in advance
Pat

Try

{{ range (where .Data.Pages "Section" "post").Reverse }} {{.Title}}</br>  {{ end }}
3 Likes

bep,
Bingo - sort only posts by date reversed - latest at top, where I wanted the date and the title with a link

  {{ range (where .Data.Pages "Section" "post").ByDate.Reverse }}
    {{ .Date.Format  "Jan 02, 2006" }} » <a href="{{ .RelPermalink }}">{{ .Title }}</a><br/>
  {{ end }}

Many thanks
Pat

You should really thank @tatsushid for this flexibility, the person behind all this where, bydate, reverse … clevernes.

Is it possible to have the sorting logic to sort by publishdate if available else sort by date?

Example:

post1: date=2017/01/02
post2: date=2017/01/03 publishdate=2017/01/04
post3: date=2017/01/05
post4: date=2017/01/06 publishdate=2017/01/01

Then the post should be sorted as

post3: date=2017/01/05
post2: publishdate=2017/01/04
post1: date=2017/01/02
post4: publishdate=2017/01/01

So the sorting is done in the descending order by date, but the publishdate is used instead of date if publishdate is set.

Does publishdate not already default to date when publishdate is not set in the front matter? I thought so, and perhaps might be worth to test.

No it does not.

If you have posts where only few have publishdates, then neither {{ range .Data.Pages.ByDate }} nor {{ range .Data.Pages.ByPublishDate }} do the right thing.