Skip to content

Jekyll's layouts

Cesar Gozurreta edited this page May 30, 2019 · 2 revisions

Jekyll includes a very simple way of reusing templates. I will explain how to apply existing layouts to new pages and how to create new layouts. Before we begin, let's define what layouts are: Layouts are pre-defined pieces of HTML that can be stored and used, in separate parts of a website, they can also be combined and edited to fit any page you might want them to be applied into.

How to use an existing layout:

each page included in the website is preceded by information written in YAML referred to as Front Matter. This data is read by Jekyll and used to assign a layout to said page:
---
layout: home
date: 2019-05-19
category: post
---

Written in bold we can find the Front Matter that designates what layout should be applied to the current page. In this case, there should be a home layout in the _layouts/ folder. This page will automatically use whatever's included in the _layouts/home.html file

How to create a layout:

The most straightforward way to create a layout would be to write whatever HTML code we want to utilize in the assigned page e.g:

_layouts/home.html:
<h2 class="header">This is my header</h2>
{{content}}
<footer class="footer">This is my footer</footer>

the "{{content}}" tag is where the content of the page is rendered, the header and the footer will be included at the top and bottom of the page respectively.

A more sophisticated and reusable way to build a layout would be to use the {% include file-name.html %} tag. this way, the different pieces of code can be further compartmentalized and reused. In order to organize the different components, we will create separate HTML files and place them in an _includes/ folder, located in the root folder e.g:

_includes/header.html:
<h2 class="header">This is my header</h2>

_includes/footer.html:
<footer class="footer">This is my footer</footer>

_layouts/home.html:
{% include header.html %}
{{content}}
{% include footer.html %}

Clone this wiki locally