Introduction
Jekyll can act purely as a content manager and hand off the displaying and interaction of content to JavaScript. This is useful if you have a site or component that needs user interaction with JavaScript but you also want an easy way to manage the content in a markdown or data file. The easiest way to get JavaScrip to understand your content is using JSON.
Jsonify
If the data is an array or hash you can use the jsonify
filter to convert it to JSON.
---
colors:
- red
- blue
- green
---
<script>
var colors = {{ page.colors | jsonify }};
</script>
Which generates a JSON array of colors.
...
var colors = ["red","blue","green"];
...
Liquid
If we need more control over the output we can always build a JSON object ourselves.
var posts = [
{% for post in site.posts %}
{
"title": "{{ post.title }}",
"category": "{{ post.category }}",
"url": "{{ post.url }}"
}
{% unless forloop.last %},{% endunless %}
{% endfor %}
];
This gives us complete control over the JSON and allows us to run variables through filters.
[
{
"title":"Where Did The Cookie Come From",
"category":"Information",
"url":"/information/2016/01/02/where-did-the-cookie-come-from.html"
},
{
"title":"What Is Sour Dough",
"category":"Information",
"url":"/information/2016/01/01/what-is-sour-dough.html"
}
]
Use case
Katy DeCorah shows us a real application of this technique in her JekyllConf 2016 talk, Unconventional Use Cases For Jekyll.
Katy creates a map which shows the location of all the speakers at the conference. Hovering over a country displays the speakers in that country.
It’s all controlled by a Jekyll data file which is output to JSON.
- speaker: Ire Aderinkokun
twitter: ireaderinokun
country: Nigeria
talk: Using Jekyll For Rapid CSS Testing
- speaker: Amy Johnston
twitter: amybeukenex
country: Netherlands
talk: Jekyll For Technical Documentation
- speaker: Julio Faerman
twitter: jmfaerman
country: Brazil
talk: Jekyll On AWS
- speaker: Bud Parr
twitter: budparr
country: United States
talk: Real World Content Strategy With Jekyll
...
This is a great demonstration of separating content from logic. The YAML file only contains the speaker information which makes it easy to add, remove or edit speakers. The JavaScript is simpler as it won’t be polluted with speaker content.
The code for the site is available here.