Reputation: 431
I want to get the first post.content from a list of posts that belongs to two (or multiple) different categories.
The following does work, but does not exclude all but the first result:
{% for post in site.categories.categorie_A and for post in site.categories.categorie_B %}
{{ post.content }}
{% endfor %}
Placing a limit on this, will result in nothing (while it should work):
{% for post in site.categories.categorie_A and for post in site.categories.categorie_B limit:1 %}
{{ post.content }}
{% endfor %}
This does not work either:
{% for post in site.categories.categorie_A limit:1 and for post in site.categories.categorie_B limit:1 %}
{{ post.content }}
{% endfor %}
Even an if statement does not make this work:
{% for post in site.categories.categorie_A and for post in site.categories.categorie_B %}
{% if forloop.first == true %}
{{ post.content }}
{% endif %}
{% endfor %}
Aswell as nested for loops:
{% for post in site.categories.categorie_A %}
{% for categorie_A_post in post.categories.categorie_B %}
{{ categorie_A_post.content }}
{% endfor %}
{% endfor %}
Upvotes: 0
Views: 1819
Reputation: 12592
It it also possible to write this using the forloop variable. The forloop variable also works in case you want the second or third result:
{% for post in site.posts %}
{% if post.categories contains "categorie_A" and post.categories contains "categorie_B" %}
{% if forloop.first == true %}
{{ post.content }}
{% endif %}
{% endif %}
{% endfor %}
Learn more about this variable here. Good luck!
Upvotes: 0
Reputation: 52809
Or something like :
{% for p in site.posts %}
{% if p.categories contains "categorie_A" and p.categories contains "categorie_B" %}
<p>{{ p.title }}</p>
{% break %}{% comment %}Exit the loop{% endcomment %}
{% endif %}
{% endfor %}
Upvotes: 1
Reputation: 431
I found this works, not pretty but it works.
{% for post in site.posts %}
{% if post.categories contains "categorie_A" and post.categories contains "categorie_B" %}
{% capture times_if %}{% increment times_if %}{% endcapture %}
{% if times_if == '0' %}
{{ post.content }}
{% endif %}
{% endif %}
{% endfor %}
and a little bit cleaner (without "and")
{% for post in site.posts %}
{% if post.categories contains "categorie_A" %}
{% if post.categories contains "categorie_B" %}
{% capture times_if %}{% increment times_if %}{% endcapture %}
{% if times_if == '0' %}
{{ post.content }}
{% endif %}
{% endif %}
{% endif %}
{% endfor %}
Upvotes: 0