How to include HTML files in Jekyll

Amit Merchant · July 7, 2020 ·

Sometimes, there comes a scenario where you would need to extract some part of the html so that you can use it across different areas of your site without repeating the same markup all over places.

For instance, the “Recently Published” section of the sidebar on this site contains 5 recently added articles. Now, I want to make this section re-usable. Jekyll makes it easy to accomplish this.

So, to make the logic re-usable, I created a file called recent_articles.html under the _includes folder like so.

<div class="recent-articles">
    <h2>Recently Published</h2>
    {% assign maxposts = 5 %}
    <ul class="post-list text-muted list-unstyled">
        {% for post in site.posts limit: maxposts %}
            <li>
                <p>
                    <a class="article-link" href="">
                    {{ post.title | escape }}</a>
                </p>
            </li>
        {% endfor %}
    </ul>
</div>

Note: Keep in mind, the _includes is the only folder where all your html goes that you want to “include” at various places.

Now, all I need to do to include is to use following format in the file you want include the file.

In my case, I wanted to include this in sidebar.html and here’s how I included it.

{% include recent_articles.html %}

This way, Jekyll will render the included file and is become re-usable as well.

Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Newsletter

Follow me on Twitter @amit_merchant