includes in Jekyll's layouts
12 Apr 2020 - Kovacs J Giulia
The include
tag allows you to include content from another file stored in an _includes
folder. Includes are useful for having a single source for source code that repeats around the site or for improving the readability.
Navigation source code can get complex so sometimes it’s nice to move it into an include.
Jekyll supports loading data from YAML, JSON, and CSV files located in a _data
directory. Data files are a great way to separate content from source code to make the site easier to maintain.
Create a data file for the navigation at _data/mynavigation.yml
with the following:
- name: Home
link: /
- name: About
link: /about.html
Jekyll makes this data file available to you at site.data.navigation
. Instead of outputting each link in _includes/mynavigation.html
, you can iterate over the data file instead.
Create a file for the navigation at _includes/mynavigation.html
with the following content:
<nav> ¤
{% for item in site.data.mynavigation %}
<a href="{{s item.link | relative_url } }"
{% if page.url == item.link %}style="color: red;"{% endif %}>
{{ item.name } }
</a> ¤
{% endfor %}
</nav>
Use the include tag to add the navigation to _layouts/mydefault.html
:
---
layout: default
---
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>{{ page.title } }</title>
</head>
<body>
{% include navigation.html % }
{{ content } }
</body>
</html>
K.i.s.s. & write:
---
layout: default
---
{% include navigation.html % }
{{ content } }
jekyll