Nested liquid loops in a Jekyll archive page not working. Using an outer loop variable inside the inner's condition
I am working with the jekyll static site builder, and I am having difficulty performing the following:
{% for category in site.categories %}
<h2 id = "{{ category[0] }}"> {{ category[0] }} </h2>
{% for post in site.categories[{{ category }}] %}
<li> <a href="{{ post.url }}"> {{ post.title }}</a></li>
{% endfor %}
<a href="#{{ category[0] }}-ref">↩</a>
{% endfor %}
I have a post category in my jekyll site called 'test', and I can display p开发者_运维知识库osts from it with the following:
{% for post in site.categories.test %}
<li> <a href="{{ post.url }}"> {{ post.title }}</a></li>
{% endfor %}
However, i want to build an archive page automatically, and in order to do this, I need to embed the category from the outer loop (the loop that visits all the categories), and use it inside the inner loop to access posts from that specific category. What do I need to do to get the first snippet to work how I want it to?
EDIT: Alternatively, is there another way to get the results that I want?
When you do for category in site.categories
,
category[0]
will give you the category name,category[1]
will give you the list of posts for that category.
That's the way Liquid handles iteration over hashes, I believe.
So the code you are looking for is this one:
{% for category in site.categories %}
<h2 id="{{ category[0] }}-ref">{{ category[0] }}</h2>
<ul>
{% for post in category[1] %}
<li><a href="{{ post.url }}">{{ post.title }}</a></li>
{% endfor %}
</ul>
<p><a href="#{{ category[0] }}-ref">↩</a></p>
{% endfor %}
I've taken the liberty of fixing some markup issues - I've added <ul>...</ul>
around the post link list, a <p>
around the last link, a semi-colon after the 8617
, and also fixed the id
at the top (was missing the -ref
part).
Regards!
How about...
{% for category in site.categories %}
<h2 id = "{{ category[0] }}"> {{ category[0] }} </h2>
<ul>
{% for post in site.posts %}
{% if post.category == category[0] %}
<li> <a href="{{ post.url }}"> {{ post.title }}</a></li>
{% endif %}
{% endfor %}
</ul>
<a href="#{{ category[0] }}-ref">↩</a>
{% endfor %}
Sure, it's pretty inefficient and generates a bunch of extra whitespace, but it gets the job done.
[The original was missing the tags. Just added them. Also, to get ride of the whitespace, one can collapse everything from for post in site.posts
to endfor
onto a single line.]
{% for post in site.categories.category %}
- OR -
{% for post in site.categories.category[0] %}
Also, I'm not sure why kshep's example doesn't work...
精彩评论