Looping Over Jekyll Collections

I am trying to create a collection within my jekyll page for book reviews.

These are my changes -

# Jekyll collections
# Documentation - https://jekyllrb.com/docs/collections/
collections_dir: collections
collections:
    books:
      output: true
      permalink: /:collection/:title

And this is my folder structure for collections

├── collections
│   ├── books
│   │   ├── index.html
│   │   └── Harry_Potter.md
│   └── index.html
├── _config.yml

Upon starting the jekyll server with jekyll serve, I’m able to see the page directly under http://localhost:4000/collections/books/Harry-Potter/

But, the index.html file under collections/ directory is not able to iterate over the list of books and display the pages.

Specifically,

  {% for collection in site.collections %}
      <section>
          <h1>{{ collection.label }}</h1>
      </section>
  {% endfor %}
</div>

gives the following output -

books
posts

But when I try to print {{ site.books.size }} as <h1>{{ site.books.size }}</h1> I get 0 as output.

And for the same reason,

{% for book in site.books %}
    <h1>{{ book.title }}</h1>
{% endfor %}

doesn’t generate any output at all.

Why is {{ site.books.size }} not able to pull up any posts?

Try renaming your books collection folder to _books

Pretty sure collection directories need to start with an underscore.

you may check that
http://talk.jekyllrb.com/t/solved-listing-pages-of-a-collection/1011

Thanks @eric-zh!

That worked perfectly.

Now, I was using pretty permalinks for my posts. And I wanted to use /:collection/:title for my books collection.

But, I think it is messing up my post url too. My current post URL turns out to be something like
http://127.0.0.1:4000/_posts/2018/05/26/Setup-Samba-File-Server/ (Notice the _posts).

Is there a way to define category specific permalink?

# Permalinks
permalink: pretty
future: true

highlighter: rouge
markdown: kramdown
plugins: ['jekyll-paginate']

# Jekyll collections
# Documentation - https://jekyllrb.com/docs/collections/
collections_dir: collections
collections:
  books:
    output: true
    permalink: /:collection/:title

Thanks @mmistakes! This had to be done as part of @eric-zh’s suggestion too.

1 Like