forked from scotte/jekyll-clean
-
Notifications
You must be signed in to change notification settings - Fork 0
Adding Search Functionality
Emily Esten edited this page Feb 5, 2020
·
5 revisions
As static sites, Jekyll pages do not typically include search functionality. This site uses @christian-fei's Simple Jekyll Search library, a JavaScript library to add search functionality to Jekyll sites. (Instructions below edited for clarity, but come from @christian-fei.)
npm install simple-jekyll-search
Place the following code in a file called search.json
in the root of your Jekyll blog. This file will be used as a small data source to perform the searches on the client side, and search both pages and posts on your site (edit as necessary):
---
layout: null
---
[
{% for post in site.posts %}
{
"title" : "{{ post.title | escape }}",
"category" : "{{ post.category }}",
"tags" : "{{ post.tags | join: ', ' }}",
"url" : "{{ site.baseurl }}{{ post.url }}",
"date" : "{{ post.date }}",
"content" : "{{ post.content | strip_html | strip_newlines }}"
} {% unless forloop.last %},{% endunless %}
{% endfor %}
,
{% for page in site.pages %}
{
{% if page.title != nil %}
"title" : "{{ page.title | escape }}",
"category" : "{{ page.category }}",
"tags" : "{{ page.tags | join: ', ' }}",
"url" : "{{ site.baseurl }}{{ page.url }}",
"date" : "{{ page.date }}",
"content" : "{{ page.content | strip_html | strip_newlines }}"
{% endif %}
} {% unless forloop.last %},{% endunless %}
{% endfor %}
]
Here is the code you can use with the default configuration. We have created a separate page for searching at this time, but it can also be configured into the header through a layouts option.
---
layout: default
---
<!-- HTML elements for search -->
<input type="text" id="search-input" placeholder="Search...">
<ul id="results-container"></ul>
<!-- Script pointing to search-script.js -->
<script src="{{ site.baseurl }}/js/search-script.js" type="text/javascript"></script>
<!-- or without installing anything -->
<script src="https://unpkg.com/[email protected]/dest/simple-jekyll-search.min.js"></script>
<!-- Configuration -->
<script>
SimpleJekyllSearch({
searchInput: document.getElementById('search-input'),
resultsContainer: document.getElementById('results-container'),
json: '{{ site.baseurl }}/search.json',
searchResultTemplate: '<li><a href="{{ site.url }}{url}">{title}</a></li>'
})
</script>