user1082754
user1082754

Reputation:

Jekyll for loop - multiple arrays

In Jekyll, I have a small blog system going with two categories: blog and portfolio. I have two pages that will render the posts for these categories, with a for loop that looks something like this:

{% for post in site.categories['blog'] %}
…
{% endfor %}

On my home page, I want to show the latest post in the blog category. However, I want my blog to contain some of my photography too - these will exist as posts, but most of the time they have no title or body content - they are just an image. I do not want those posts to show up on the home page.

Effectively, I only want the latest blog post to show up on the home page, excluding all photography posts. I am considering my options for this:

  1. Use two categories: blog and photos. However, how would I then make my blog page show posts from both of these categories? I would effectively need to merge the arrays site.categories['blog'] and site.categories['photos'], and put those into a for loop - but is that possible?
  2. Keep one category: blog, but in some other way, exclude posts without a title from appearing on the home page. But how do you do that?

Is this possible?

Upvotes: 3

Views: 3546

Answers (2)

Razzi Abuissa
Razzi Abuissa

Reputation: 4092

A straightforward approach here is to use Jekyll categories.

Put your posts into subdirectories of the _posts folder:

_posts/
    blog/
        post.md
    photos/
        photo.md

Then in your index.html or anywhere else you can refer to the separate categories as follows:

<h1>Blog</h1>

{% for post in site.categories.blog %}
    {{ post.title }}
{% endfor %}

<h2>Photos</h2>

{% for photo in site.categories.photos %}
    {{ photo.title }}
{% endfor %}

And you can access all posts using site.posts.

For a relevant github issue "Multiple _posts directories" see https://github.com/jekyll/jekyll/issues/1819#issuecomment-30441840.

Upvotes: 0

Lolindrath
Lolindrath

Reputation: 2101

On the blog page you can use:

{% for post in site.posts %}
…
{% endfor %}

To retrieve all posts and show them all. If you want to filter more (say, you have a third category you wouldn't want to show on this page:

{% for post in site.posts %}
    {% if post.categories contains 'post' or post.categories contains 'photos' %}
       ...
    {% endif %}
{% endfor %}

Upvotes: 7

Related Questions