Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jekyll — Change layout if page is a post?

Tags:

jekyll

liquid

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 }}
like image 522
Zaz Avatar asked Sep 07 '13 16:09

Zaz


4 Answers

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.

like image 188
kavinyao Avatar answered Nov 18 '22 19:11

kavinyao


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 %}
like image 20
dafi Avatar answered Nov 18 '22 19:11

dafi


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>
like image 11
kimbaudi Avatar answered Nov 18 '22 20:11

kimbaudi


Here's how I solved the problem:

  1. Create a symlink from _layouts/post_layouts/main
  2. Change the layout of posts to post:

    ---
    layout: post
    ---
    
  3. 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.

like image 9
Zaz Avatar answered Nov 18 '22 19:11

Zaz