In a Jekyll layout, is there any way to detect if the page is a normal page or a post? I want to display post titles, but not page titles. Like this:
{% if page.is_post? %}
<h2>{{ page.title }}</h2>
{% endif %}
{{ content }}
Since Jekyll 2.0, you can use Front Matter Defaults:
defaults:
-
scope:
path: "" # empty string for all files
type: posts # limit to posts
values:
is_post: true # automatically set is_post=true for all posts
then you can use {{ page.is_post }}
to check whether the page is post.
No idea why Jekyll doesn't set page.type
by default.
Declaring a post layout in front-matter is not enough?
If your post uses a post
layout you are sure the page is a post and you don't need to add extra logic
---
layout: post
---
BTW a quick and dirty (very dirty) way to determine the page type consists to check the page path, generally posts are under the _posts
directory so you can check it
{% if page.path contains '_posts' %}
This page is a post
{% else %}
This page is a normal page
{% endif %}
The easiest and most straightforward way to determine if its a page or a post is to use page.id
.
{% if page.id %}
This is a post
{% endif %}
I personally use this method in my layouts page to determine if its a page or post so I can show links to previous/next posts only if its a post.
_layouts/default.html
<!DOCTYPE html>
<html lang="en">
{% include head.html %}
<body>
{% include header.html %}
{{ content }}
<!-- If this is a post, show previous/next post links -->
{% if page.id %}
{% if page.previous.url %}
<a href="{{page.previous.url}}">{{page.previous.title}}</a>
{% endif %}
{% if page.next.url %}
<a class="button is-link ellipsis" title="{{page.previous.title}}" href="{{page.next.url}}">{{page.next.title}}</a>
{% endif %}
{% endif %}
{% include footer.html %}
</body>
</html>
Here's how I solved the problem:
_layouts/post
→ _layouts/main
Change the layout of posts to post
:
---
layout: post
---
Add an if statement in _layouts/main
like so:
{% if page.layout == 'post' %}
<h2>{{ page.title }}</h2>
{% endif %}
A better way to solve this might be to use includes and have two separate layouts like @dafi said though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With