Static Data
Managing basic data with Jekyll
Collections of data are common in websites,
and we usually code these lists by hand.
With Jekyll we can store list-like data in
data files, then generate HTML lists from them.
Jekyll data files use the YAML language,
like we use in our _config.yml
file.
Data files are simple lists, where each
list item can have multiple properties.
Data Files
We can have as many data files as we like.
Each data file should store one kind of data.
In your project folder,
create a new folder called _data
.
In your data folder,
create a new file called shop.yml
Defining Data
All YAML data consists of properties and lists.
In shop.yml
create a list of shop items.
- name: Chocolate Cake
- name: Spring Water
- name: Mentos
To add extra information to items,
we add more lines under each one.
- name: Chocolate Cake
price: '5.50'
- name: Spring Water
price: '3.70'
- name: Mentos
price: '2.00'
Remember to save your data file!
Displaying Data
Data is dislayed on a page
using a Jekyll for loop.
Data files can be accessed from
any page, template or include.
To display data, we need to run a loop
to show each piece of data individually.
In your shop.html
, add a loop which
displays the name of each shop item.
<ul class="shop-items">
{% for item in site.data.shop %}
<li>
{{ item.name }}
</li>
{% endfor %}
</ul>
Visit the shop page in your web browser.
You should see a list of item names.
Add the price and some additional
HTML structure to allow for styling.
<ul class="shop-items">
{% for item in site.data.shop %}
<li>
<span class="name">{{ item.name }}</span>
<span class="price">${{ item.price }}</span>
</li>
{% endfor %}
</ul>
Your shop page should now display the item and its price.
Here’s some CSS to get you started
with styling up your shop items.
.shop-items {
list-style-type: none;
padding-left: 0;
}
.shop-items li {
padding: 5px 10px;
border-bottom: 1px solid #666;
display: flex;
}
.shop-items .name {
flex: 1;
font-weight: bold;
}
Your shop items should now be in a tidy list!
Summary
- Data Files
Simple data can be created using YAML. - Jekyll Loops
Data can be dislayed by looping over the values in a page
Static Data: Complete
Loading...