I recently added a vanilla JS search page to my blog by following my friend Chris Ferdinandi's tutorial. As part of the tutorial, I needed to get a JavaScript array of all my blog posts. Here's how I did that in Jekyll, the static site generator I use.

Note: I have since switched to Eleventy.

Here's the desired output, using only one of my posts for brevity:

var searchIndex = [
{
date: {
human: "3 April 2020",
machine: "2020-04-03"
},
excerpt: "My third challenge for the Vanilla JS Academy was to build a random quotes app using an API. Let’s look at how I approached the task.",
title: "How I built a random quotes app with vanilla JavaScript",
url: "/2020/04/03/how-i-built-a-random-quotes-app-with-vanilla-javascript.html"
}
];

Each object has the following properties: date, excerpt, title, and url.

The date object has two properties of its own: human and machine. This is because I use the date within a time element. A time element's datetime attribute needs to be in a particular machine-readable format, whereas the text content can be in a more human-readable format.

To achieve this, all I did was add the following Liquid tags directly into my JavaScript code (Liquid is the template language that Jekyll uses):

var searchIndex = [
{% for post in site.posts %}
{
date: {
human: "{{ post.date | date: '%e %B %Y' }}",
machine: "{{ post.date | date: '%Y-%m-%d' }}"
},
excerpt: "{{ post.excerpt | strip_html | escape | strip }}",
title: "{{ post.title | escape }}",
url: "{{ site.baseurl }}{{ post.url }}"
}{% unless forloop.last %},{% endunless %}
{% endfor %}
];

The above code loops through all of my posts and adds each one to my searchIndex array. Visual Studio Code thinks there are errors in my code because it doesn't recognize the Liquid tags as valid JavaScript. It doesn't matter, though, because the actual output is valid.

I got the idea from the Simple-Jekyll-Search plugin, although I didn't use it. Many thanks to its creator, Christian Fei!