Display last item of a collection


#1

Hey Jekyll-ers!

I am trying to build a podcast website out of David Darnes’s Alembic theme. So far I’ve configured a collection for episodes and everything seems to be working for the most part, yay!

Where I’m getting stuck is when I’m trying to show just the latest post on the homepage.

Here is my code so far:

<ul class="list  list--posts">
    {% for episode in site.episodes reversed limit:1 %}
      <li class="item  item--post">
        <h2><a href="{{ episode.url }}">{{ episode.title }}</a></h2>
        <small class="small  post-meta">
          <time datetime="{{ episode.date | date_to_xmlschema }}" class="time">{{ episode.date | date_to_string }}</time>
        </small>
        <p>{{ episode.content | markdownify }}</p>
      </li>
    {% endfor %}
</ul>

It’s only showing the first post, so it’s limiting it, but not reverse. I tried a pipe character but that seems to be throwing liquid errors in terminal.

Here is a live example:

Help?

Edit: Okay, it looks like I shouldn’t really be using collections for this. Categories are probably a better option as I should be able to filter through a for loop by a certain category, right?

Any thoughts?

Thanks ahead of time for the help!


#2

do you have the date in the front matter of the collection items?

this seems to say it can be done - as far as reversing the order sorted by date - not the limit part but I would think that is the easy part:


#3

This may work for you. It’s a quick way to get at first and last posts. And since posts are a collection I’m thinking it will.

You just might need to do an assign on the collection first to sort it. Then you can .first on that sorted array.


#4

Looks like I had to assign it as you said!

Here is what worked for me!

<ul class="list  list--posts">
    {% assign episodes = site.episodes %}
      <li class="item  item--post">
        <h3><a href="{{ episodes.last.url }}">{{ episodes.last.title }}</a></h3>
        <small class="small  post-meta">
          <time datetime="{{ episodes.last.date | date_to_xmlschema }}" class="time">{{ episodes.last.date | date_to_string }}</time>
        </small>
        <p>{{ episodes.last.content | markdownify }}</p>
      </li>
</ul>