Loop through posts' date in order to make arch

2019-08-12 03:42发布

问题:

Here's some pseudo-code of what I want to achieve:

for year in post.date
    h1 year
    for month in post.date
        h2 month
        ul
            li post entry

That's the pseudo-code. However I don't have enough experience to achieve this. The file in which this would happen is this one: https://github.com/Greduan/eduantech.docpad/blob/master/src/documents/posts.html.eco

And it would be in the eco language. I'm using Moment.js as well in case that's necessary.

Even if you don't provide the exact code, a general direction will be very appreciated. :)

EDIT: What I would like to achieve is something similar to this: http://swannodette.github.io/archive.html

EDIT 2: Here's some of the code that I came up with:

for post in @getCollection('posts').toJSON()

    for year in post.date
        h1 @moment(post.date).format('YYYY')

        for month in post.date
            h2 @moment(post.date).format('MMMM')
            ul ->
                li ->
                    @postDatetime(post.date, 'll') + ' » '
                    a href:'post.url', post.title

For now it just outputs nothing. So I'm thinking I just got some of the variable names wrong, which I imagine I did. I appreciate any help. :)

BTW don't worry about the @postDatetime function. That with works no problems somewhere else. :)

回答1:

If you already have your posts sorted by date, then your collection is already grouped by year,month. All you need to do is loop through the whole collection and insert your year and month headers when the year/month values change. Something like this:

yr = -1 //temporary vars for storing current year value in loop
mnth = -1 //same for month value
monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]

div style:'text-align:left;font-size:20px;width:500px;margin-right:auto;margin-left:auto', ->

for post in @getCollection('posts').toJSON()
    if post.date.getFullYear() isnt yr
        yr = post.date.getFullYear()
        mnth = -1 
        h1 yr.toString()
    if post.date.getMonth() isnt mnth
        mnth = post.date.getMonth() 
        h2 style:'padding-left:10px;', monthNames[mnth]
        ul style:'padding-left:50px;', ->
    li ->
        post.date.toDateString()

Does that sound like what you are after?