Jekyll Includes

Episode #4 - Mar 18, 2016 - 4 minutes

Subscribe to Jekyll Casts

On this index.html page you can see there’s a subscribe to our newsletter section.

Newsletter section

And let’s say now, we also way this newsletter section on blog.html. One way of doing this would be to copy the newsletter section HTML and paste it into blog.html. This works however now we’ve duplicated source code on the website. If we ever wanted to change content inside the newsletter section, then we’d have to make the change in multiple places. A better solution is to use Jekyll includes.

To use includes we’ll create a new folder called _includes. Inside this we’ll create a new file called newsletter.html. Now we’ll copy the source code for the newsletter section across to newsletter.html.

<div class="newsletter spacing">
  <form action="">
    <h3>Subscribe to our mailing list!</h3>
    <label for="email">Email</label>
    <input type="email" name="email" id="email">

    <input type="submit" value="Subscribe">

In index.html we can replace the newsletter section with the include:

{% include newsletter.html %}

We can also use this newsletter include on blog.html. Now if we change newsletter.html it’s reflected on both pages.

In more complicated situations you can also pass parameters to an include. In this example we’re going to add YouTube videos to the site which we always want presented in a consistent way. We need them to be centered and a particular size.

Let’s create a new include, _includes/youtube.html. In this file we’ll create the structure for displaying a YouTube video and have a placeholder for the YouTube video id. We can access parameters passed to an include using include.variable_name.

<div class="spacing youtube">
  <iframe width="560" height="315" src="{{ include.youtube_id }}" frameborder="0" allowfullscreen></iframe>

Now we can use this include throughout our site and pass in the video id we want to display:

{% include youtube.html youtube_id="YIiHiMXOeYU" %}

Subscribe to Jekyll Casts