4
votes

I have Jekyll blog where some posts have "featured images," some posts don't.

Featured images are defined in the front matter of the post like so: featured-image: http://path/to/img

On the archive page, I'd like to grab the three most recent posts that have featured images and display them.

I imagine this would need an if statement, a counter, and a loop, but I can't get this one to work for me:

<ul id="archive-featured">
  {% assign count = '0' %}
  {% if count < '4' %}
    {% for post in site.posts %}
      {% if post.featured-image == true %}
        {{ count | plus: '1' }}
        <li><a href="{{ post.url }}"><img src="{{post.featured-image}}" />{{ post.title }}</a></li>
      {% endif %}
    {% endfor %}
  {% endif %}
</ul>

What am I missing?

2
I'm also looking for something like this - > where I'll skip showing a "Related" headline at all, if count is 0. So I'd like to count first, and then loop through them if count > 0.Alisso

2 Answers

4
votes

Your YAML matter looks good, but I am not sure you need the count assignment to make this work. Try using limit instead to restrict the number of posts your assign on your archive page. You also do not need to assign a "true" value for the {% if %} statement to work:

<ul id="archive-featured">
{% for post in site.posts limit:3 %}
  {% if post.featured-image %}
    <li>
      <a href="{{ post.url }}">
        <img src="{{ post.featured-image }}" />
        {{ post.title }}
      </a>   
    </li>
  {% endif %}
{% endfor %}
</ul>

I believe that the posts are automatically displayed by most recent post, so no extra work needs to be done there. Hope this helps!

0
votes

A very late answer:
I think the problem is with {{count | plus: 1}}. Wouldn't this just ouput the count + 1, but not assign it? You can solve this like by assign a new variable before the end of the forloop

<ul id="archive-featured">
  {% assign count = 0 %}
  {% if count < 4 %}
    {% for post in site.posts %}
      {% if post.featured-image == true %}

        <li><a href="{{ post.url }}"><img src="{{post.featured-image}}" />{{ post.title }}</a></li>
{% count | plus: 1 %}
      {% endif %}
    {% endfor %}
  {% endif %}
</ul>

A workarounds that might be interesting: If you add another simple statement to your front matter, like featured: true you can use the where filter to select only those posts. (The where filter sadly doesn't seem to work with comparisons)

<ul id="archive-featured">
  {% assign posts=site.posts | where "featured", "true" %}
    {% for post in posts | limit: 3%}
        <li><a href="{{ post.url }}"><img src="{{post.featured-image}}" />{{ post.title }}</a></li>
    {% endfor %}
</ul>