Jekyll is a static site generator with some great ideas to help us structure a website. By taking advantage of some of these ideas, you can decouple the complicated part of the project and build them as separate components.

Jekyll provides a tag called include, which you can use to include content from other documents. Using the include tag, you can avoid repetition and keep the code clean by passing parameters into the include component.1

For example, we’re going to create a related_card.html component that you can include at the end of your post. You will have to place the file inside includes directory. I usually create another folder called components and group these components together.

Here is the structure of the directory:

_includes/
  components/
    related_card.html
  custom/
  footer.html
  head.html
  header.html
  main.html
  sidebar.html

Here is the content of the related_card.html.


<div class="related_card">
  <h4>{{ include.title }}</h4>
  <p>{{ include.description }}</p>
  <a href="{{ root_url }}{{ include.url }}">Read More</a>
</div>

You need to prepend include before each parameter because that’s how you will access these parameters later on.

How to Include the Component

If you’re using Jekyll for your blog, you will find a layout called _post.html that renders how a blog post should look. Here’s how you can include the related_card.html and pass values into the component.


{% include components/related_card.html 
  title = "The Post Title"
  description = "Here is the description"
  url = "Here is the site URL"
%}

This approach is useful when you need to iterate through a collection, data or when you want to create an archive page with the card format as part of the layout. Here is how you can iterate all the posts on your site.


{% for post in site.posts %}
  {% include components/related_card.html 
    title = post.title
    description = post.description
    url = post.url
  %}
{% endif %}

Once you’ve familiarized yourself with include, you can start removing some repetitive parts from your project and put them inside the components folder. You will be able to make changes without having to edit each page layout.

  1. Read the official documentation to learn more what you can do with include