Logo

mobileteashop

Dennis Poon's blog and ersatz portfolio.

Sub-Templates in Jekyll

Jekyll has been generally intuitive to use, but there are a few things that the documentation and most tutorials on the web deign not to explain/illustrate well.

In particular, sub-templates in Jekyll are often described as to ‘behave just as you’d expect’. However, I wouldn’t know what to expect because I have no idea how to structure one! A simple example or two would be very helpful, especially when comparing sub-templates with the include mechanism.

To be fair, once you see a sub-template, they really do behave as expected. So to close that gap, here is an example of a sub-template in Jekyll.

Start with a parent template like this:

_layouts/parent.html

<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
</head>
<body>
  <h1>My Template</h1>
  
  <div class="content">

  {{ content }}

  </div>
</body>
</html>

To create a sub-template, reference the desired parent template in the YAML front-matter then fill it in like this:

_layouts/child.html

---
layout: parent
---
<h2>My Sub-Template</h2>
<p>I'm in my sub-template.</p>
<div>
  {{ content }}
</div>

The content of the sub-template will be inserted in its entirety where {{ content }} is specified in the parent. Pages then using the sub-template will have the effective combined template of:

<!DOCTYPE html>
<html>
<head>
  <title>My Website</title>
</head>
<body>
  <h1>My Template</h1>
  
  <div class="content">

    <h2>My Sub-Template</h2>
    <p>I'm in my sub-template.</p>
    <div>
      {{ content }}
    </div>

  </div>
</body>
</html>

In this way, you can nest as many templates as you’d like. However, you cannot perform the inverse - i.e. have the parent pull-in one or more sub-templates. If you need to do this, you can sort of approximate it using Jekyll include (though this mechanic also has its limitations).

Most of my initial confusion with Jekyll came when figuring out the appropriate uses and limitations of _includes/ and _layouts/. I will likely follow up on include in another post.