Why doesn't this Jekyll Liquid where filter fi

2020-08-17 02:52发布

问题:

I am trying to output a list of blog posts for a certain author. I tried this where Jekyll filter:

{% for post in (site.posts | where:"author", "mike") %}
  {{ post.title }}
{% endfor %}

But it outputs every post. I'm not clear what I'm doing wrong.

回答1:

Supposing that your post author is in your front matter, like this :

---
author: toto
...
---

If you want two last post by author == toto, just do :

{% assign counter = 0 %}
{% assign maxPostCount = 2 %}
<ul>
{% for post in site.posts %}
  {% if post.author == 'toto' and counter < maxPostCount %}
    {% assign counter=counter | plus:1 %}
    <li>{{ counter }} - {{ post.title }}</li>
  {% endif %}
{% endfor %}
</ul>

Et hop !

EDIT : And another solution using the where filter instead of the if clause :

{% assign posts = site.posts | where: "author", "toto" %}
{% assign counter2 = 0 %}
{% assign maxPostCount2 = 3 %}
<ul>
{% for post in posts %}
  {% if counter2 < maxPostCount2 %}
    {% assign counter2=counter2 | plus:1 %}
    <li>{{ counter2 }} - {{ post.title }}</li>
  {% endif %}
{% endfor %}
</ul>

RE-EDIT: Justin is right I don't need my two vars (counter2 and maxPostCount2), I can use Liquid for loop limit:n option.

{% assign posts = site.posts | where: "author", "toto" %}
<ul>
{% for post in posts limit:3 %}
  <Ol>{{ post.title }}</ol>
{% endfor %}
</ul>

Better !



回答2:

You need to do an assign first for the filtered items

{% assign posts = site.posts | where:"author", "mike" %}
{% for post in posts %}  
   {{ post.title }}
{% endfor %}


回答3:

It seems filters are to be used only inside output tags (those surrounded by {{ and }}. Which mean you could use something like :

{{ site.posts | where "author", "mike" }}

But you can't use it the way you're doing.

Source: liquid documentation on Filters



标签: ruby jekyll