Blair Anderson
Blair Anderson

Reputation: 20171

jekyll: combine limit and where and reverse

Using Jekyll i'd like to:

i'm having problems when getting all those filters together

{% assign posts = site.posts | reverse %}
{% for post in posts limit:3 %}
  {% if post.categories contains 'featured' and post.path != page.path %}
    {% include card.html post=post %}
  {% endif %}
{% endfor %}

right now the limit is not working properly because the inner if will prevent a few items from being rendered.

Upvotes: 1

Views: 270

Answers (1)

Robin James Kerrison
Robin James Kerrison

Reputation: 1767

Assign 0 to a counter variable before entering your loop. Don't set a limit on the loop, but instead set another condition on your counter being below your limit, and increment the counter using Liquid's plus filter every time you meet your criteria and output the card.

{% assign posts = site.posts | reverse %}
{% assign counter = 0 %}
{% for post in posts %}
  {% if counter < 3 and post.categories contains 'featured' and post.path != page.path %}
    {% include card.html post=post %}
    {% assign counter = counter | plus: 1 %}
  {% endif %}
{% endfor %}

A more complex example

I'm basing all of this on the looping I use myself. My condition is a little more complex: I check for any shared tag with the current page. I've included this as a further example below.

{% assign counter = 0 %}
{% for post in site.posts %}
    {% if counter < 4 %}
        {% if post.url != page.url %}
            {% assign isValid = false %}
            {% for page_tag in page.tags %}
                {% for post_tag in post.tags %}
                    {% if post_tag == page_tag %}
                        {% assign isValid = true %}
                    {% endif %}
                {% endfor %}
            {% endfor %}
            {% if isValid %}
                {% include article_card.html %}
                {% assign counter = counter | plus: 1 %}
            {% endif %}
        {% endif %}
    {% endif %}
{% endfor %}

Why where fails

Although Liquid has a where filter, it can only do exact comparisons, so you have to reinvent the wheel like this in order to achieve the where-like scenario for more complex conditions. This does make for a lot of looping through site.posts, but Jekyll being a preprocessor means the penalty of using a somewhat inefficient improvised where-type looping is only a compile-time concern, not a runtime one. Even so, to mitigate this cost as much as possible, I opt for having the counter condition be the first that Jekyll calculates.

Upvotes: 1

Related Questions