Determine Which File is Loading a Layout File

In my Jekyll project I have a layout file named default. This file is aimed to hold code that is common for any other layout, which helps me to maintain such code more easily.

There are "holes’ ’ in this code that must be filled with content that is specific to the layout file that is calling the default. I need a way to detect which file is calling the default layout, so the proper action is taken.

To understand what I want to do, please consider the (simplified) example bellow:

_includes/post_metadata.html:

<!-- Lines of code to be loaded in the <head> element 
of the post_layout.html -->

<link rel="stylesheet" type="text/css" href="post.css">

_layouts/default.html

<!-- Code to be reused in several layouts -->
<html>
  <head>
    {% if <is_post_layout> %}
      {% include post_metadata.html %}
    {% endif %}
  </head>
  <body>
    {{ content }}
  </body>
</html>

_layouts/post_layout.html

---
layout: default
---
<!-- Contains article-specific HTML structure, but uses the 
default layout as a base-->
<article>
  {{ content }}
</article>

_posts/2021-09-22-post.md:

---
layout: post_layout
---
<!-- Post content -->
[...]

The final page generated by Jekyll should contain:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="post.css">
  </head>
  <body>
    <article>
      [...]
    </article>
  </body>
</html>

So, what code should I use to replace <is_post_layout> to make it work?

What are want to check is whether the current page has layout of post or not. Assuming you have set the layout to be post on each post or on config defaults (much more efficient to apply for all posts).

So use a page variable

page.layout

Docs - page variables

And check against your value

{% if page.layout == 'post' %}
1 Like

Also I imagine the amount of CSS for a post will only be tens of lines.

So why not just load the post.css file on every page?

The browser will cache assets like CSS files. So if someone lands on your homepage, they’ll get the main CSS and post CSS loaded. and then on every page load throughout the rest of the site, the browser will see oh I already have the CSS file so I won’t refetch it from the server (you’ll see a 304 instead of 200 in your browser Network tab).

Or roll the main CSS and post.css into one file?

And you can also use a processor to minify your CSS if you are concerned about that.

1 Like

It’s actually hundreds of lines. I don’t want the first load of the website to appear sluggish to the user. Besides that, if the user cleans its browser cache regularly, the caching won’t help as much. Minifying CSS is really helpful, but has not been enough But thanks.for the considerations. :+1:t3:

1 Like