Newbie to Jekyll. I’ve got custom variables like these in the frontmatter:
film: Avatar (2009)
film: Spider-Man (2002)
If I want to display all posts with this variable, how can I do that?
An example would be really helpful. Thanks in advance.
Newbie to Jekyll. I’ve got custom variables like these in the frontmatter:
film: Avatar (2009)
film: Spider-Man (2002)
If I want to display all posts with this variable, how can I do that?
An example would be really helpful. Thanks in advance.
Jekyll treats front matter like any other piece of data. You can add [pretty much] anything you want there, and it will be available for you to use programmatically.
Let’s say you are writing a post about Avatar and want to reference the film:
front matter in the content of your post. You can use this example to display it within the post:
/_posts/2022-06-20-all-about-avatar.md
---
title: All about Avatar
date: 2022-06-20
film: Avatar (2009)
---
## {{page.title}}
This is my review of {{page.film}}.
The result would look something like this:
Even though that is technically a post, you do not use use post.film
, because, at this point, you are displaying front matter on a page, which is why you should use page.film
.
Let’s say you want a summary page that lists all the posts you made about films. Here is a basic method to do that:
/index.md
---
layout: default
title: "All my posts about films!"
---
## {{page.title}}
<p></p>
{%- for post in site.posts -%}
Title: <a href="{{post.url |relative_url}}">{{post.title}} / {{post.film}}</a><br>
{%- endfor -%}
The result will be a list of all posts on your site, like this:
Notice in the screenshot that there is a post without the title Introducing my new blog.
That post does not have the film
YAML front matter, which may be fine for you. However, it is not a list of films, so you will need to modify your code a bit with assign
, using a where_exp
, like this:
/index.md
---
layout: default
title: "All my posts about films!"
---
## {{page.title}}
<p></p>
{%- assign posts = site.posts | where_exp: 'post', 'post.film' -%}
{%- for post in posts -%}
Title: <a href="{{post.url |relative_url}}">{{post.title}} / {{post.film}}</a><br>
{%- endfor -%}
Now, the output will look like this:
You might be wondering how that where_exp
works. It says, “look in site.posts and only give me the results if there is a film:
front matter item”.
If you find you will be writing about films, tv shows, books, or other topics, you might want to make your life a little easier and use Jekyll Collections.
With Collections, you can create the equivalent of a _posts
folder for your films, like /_films
and tv shows, like /_tv
and so on.
Here is the official documentation for Jekyll Collections
:
Here is a post on how to use collections in a similar fashion you may (or may not) want to use:
Wow! Exactly what I need.
Thank you so much for your time & effort in writing such a detailed tutorial.
Great, and no problem!