How-to Include Components in Jekyll

This post shows how to include components in Jekyll.


Table of contents:

# What is components?

Components are reusable HTML elements that can be used again and again. Some components can be very small and simple while other components can be complex and have extensive code. Components are essentially reusable building blocks that can be used in many places on a website. For example, this progressbar,

I am a progress bar! (progressbar title)
63%

which I added to the post by adding this include code in the post’s .md file:

{% include components/progressbar.html
    percent='63'
    color='green'
    title='I am a progress bar! (progressbar title)' %}

This small piece of include code is an example of Jekyll includes.

It is this include code that allows to include components on the pages of the website. The Liquid templating language allows for dynamic behavior by evaluating logic and rendering content accordingly. The evaluation and rendering happens automatically when exporting the Jekyll website to the _site folder such that the website is still static when served on the webserver as usual.

# How-to add a progress bar as a component

The first step is to create a .html file for the progress bar.

# Adding HTML

I added a file called progressbar.html to the _includes/components folder with the following code,

<div>
    {% if include.title %}<b>{{ include.title }}</b>{% endif %}
    <div class="progressbar-container"> 
        <div class="progressbar-percent {% if include.color%} {{ include.color }} {% else %} default {% endif %}" style="width:{{ include.percent }}%;">
        {{ include.percent }}%
        </div> 
    </div> 
</div>

It is important to note that the outer <div></div> tags are necessary to prevent the Jekyll engine of nesting the component in <p></p> tags when building the site as this might prevent the code from working as expected.

Note that the

{% if include.variable %}<b>{{ include.variable }}</b>{% endif %}

tags allows to use information from the include call in the post as variables in the component. For more information refer to the Jekyll Liquid documentation.

# Styling with Sass / CSS

I style the progressbar with Sass; however, it is possible to use ordinary CSS etc.

In my components .scss file I added the following code:

.progressbar-container { 
	background-color: $default-bg; 
	width: 100%; 
	border-radius: 12px; 
	margin: 1em 0px;
} 

.progressbar-percent { 
	color: white; 
	font-size: 1rem;
	text-align: right;
	padding: 10px; 
	border-radius: 12px; 
	
	&.default {background-color: $default-bg;}
	&.yellow {background-color: $yellow;}
	&.red {background-color: $red;}
	&.green {background-color: $green;}
} 

Where the variables prefixed by $ are color variables that are defined in a Sass file for variables.


Return to top

Written by Magnus · · # Jekyll, Liquid, HTML, Sass, CodingDisclaimer · Privacy Policy