• This repository has been archived on 16/Mar/2022
  • Stars
    star
    1,321
  • Rank 35,591 (Top 0.8 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 11 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JavaScript library to add search functionality to any Jekyll blog.

Simple-Jekyll-Search

Build Status dependencies Status devDependencies Status

A JavaScript library to add search functionality to any Jekyll blog.

Use case

You have a blog, built with Jekyll, and want a lightweight search functionality on your blog, purely client-side?

No server configurations or databases to maintain.

Just 5 minutes to have a fully working searchable blog.


Installation

npm

npm install simple-jekyll-search

Getting started

Create search.json

Place the following code in a file called search.json in the root of your Jekyll blog. (You can also get a copy from here)

This file will be used as a small data source to perform the searches on the client side:

---
layout: none
---
[
  {% for post in site.posts %}
    {
      "title"    : "{{ post.title | escape }}",
      "category" : "{{ post.category }}",
      "tags"     : "{{ post.tags | join: ', ' }}",
      "url"      : "{{ site.baseurl }}{{ post.url }}",
      "date"     : "{{ post.date }}"
    } {% unless forloop.last %},{% endunless %}
  {% endfor %}
]

Preparing the plugin

Add DOM elements

SimpleJekyllSearch needs two DOM elements to work:

  • a search input field
  • a result container to display the results

Give me the code

Here is the code you can use with the default configuration:

You need to place the following code within the layout where you want the search to appear. (See the configuration section below to customize it)

For example in _layouts/default.html:

<!-- HTML elements for search -->
<input type="text" id="search-input" placeholder="Search blog posts..">
<ul id="results-container"></ul>

<!-- or without installing anything -->
<script src="https://unpkg.com/simple-jekyll-search@latest/dest/simple-jekyll-search.min.js"></script>

Usage

Customize SimpleJekyllSearch by passing in your configuration options:

var sjs = SimpleJekyllSearch({
  searchInput: document.getElementById('search-input'),
  resultsContainer: document.getElementById('results-container'),
  json: '/search.json'
})

returns { search }

A new instance of SimpleJekyllSearch returns an object, with the only property search.

search is a function used to simulate a user input and display the matching results. 

E.g.:

var sjs = SimpleJekyllSearch({ ...options })
sjs.search('Hello')

💡 it can be used to filter posts by tags or categories!

Options

Here is a list of the available options, usage questions, troubleshooting & guides.

searchInput (Element) [required]

The input element on which the plugin should listen for keyboard event and trigger the searching and rendering for articles.

resultsContainer (Element) [required]

The container element in which the search results should be rendered in. Typically a <ul>.

json (String|JSON) [required]

You can either pass in an URL to the search.json file, or the results in form of JSON directly, to save one round trip to get the data.

searchResultTemplate (String) [optional]

The template of a single rendered search result.

The templating syntax is very simple: You just enclose the properties you want to replace with curly braces.

E.g.

The template

var sjs = SimpleJekyllSearch({
  searchInput: document.getElementById('search-input'),
  resultsContainer: document.getElementById('results-container'),
  json: '/search.json',
  searchResultTemplate: '<li><a href="{{ site.url }}{url}">{title}</a></li>'
})

will render to the following

<li><a href="/jekyll/update/2014/11/01/welcome-to-jekyll.html">Welcome to Jekyll!</a></li>

If the search.json contains this data

[
    {
      "title"    : "Welcome to Jekyll!",
      "category" : "",
      "tags"     : "",
      "url"      : "/jekyll/update/2014/11/01/welcome-to-jekyll.html",
      "date"     : "2014-11-01 21:07:22 +0100"
    }
]

templateMiddleware (Function) [optional]

A function that will be called whenever a match in the template is found.

It gets passed the current property name, property value, and the template.

If the function returns a non-undefined value, it gets replaced in the template.

This can be potentially useful for manipulating URLs etc.

Example:

SimpleJekyllSearch({
  ...
  templateMiddleware: function(prop, value, template) {
    if (prop === 'bar') {
      return value.replace(/^\//, '')
    }
  }
  ...
})

See the tests for an in-depth code example

sortMiddleware (Function) [optional]

A function that will be used to sort the filtered results.

It can be used for example to group the sections together.

Example:

SimpleJekyllSearch({
  ...
  sortMiddleware: function(a, b) {
    var astr = String(a.section) + "-" + String(a.caption);
    var bstr = String(b.section) + "-" + String(b.caption);
    return astr.localeCompare(bstr)
  }
  ...
})

noResultsText (String) [optional]

The HTML that will be shown if the query didn't match anything.

limit (Number) [optional]

You can limit the number of posts rendered on the page.

fuzzy (Boolean) [optional]

Enable fuzzy search to allow less restrictive matching.

exclude (Array) [optional]

Pass in a list of terms you want to exclude (terms will be matched against a regex, so URLs, words are allowed).

success (Function) [optional]

A function called once the data has been loaded.

debounceTime (Number) [optional]

Limit how many times the search function can be executed over the given time window. This is especially useful to improve the user experience when searching over a large dataset (either with rare terms or because the number of posts to display is large). If no debounceTime (milliseconds) is provided a search will be triggered on each keystroke.


If search isn't working due to invalid JSON

  • There is a filter plugin in the _plugins folder which should remove most characters that cause invalid JSON. To use it, add the simple_search_filter.rb file to your _plugins folder, and use remove_chars as a filter.

For example: in search.json, replace

"content": "{{ page.content | strip_html | strip_newlines }}"

with

"content": "{{ page.content | strip_html | strip_newlines | remove_chars | escape }}"

If this doesn't work when using Github pages you can try jsonify to make sure the content is json compatible:

"content": {{ page.content | jsonify }}

Note: you don't need to use quotes " in this since jsonify automatically inserts them.

Enabling full-text search

Replace search.json with the following code:

---
layout: none
---
[
  {% 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 %}
]

Development

  • npm install
  • npm test

Acceptance tests

cd example; jekyll serve

# in another tab

npm run cypress -- run

Contributors

Thanks to all contributors over the years! You are the best :)

@daviddarnes @XhmikosR @PeterDaveHello @mikeybeck @egladman @midzer @eduardoboucas @kremalicious @tibotiber and many others!

Stargazers over time

Stargazers over time

More Repositories

1

Timeline.css

Share life and work events with Timeline.css! Sass and SCSS port too!
CSS
110
star
2

minimal-analytics

Read more at https://cri.dev/posts/2021-04-28-fullstack-nodejs-preact-minimal-web-analytics-introduction/
JavaScript
56
star
3

crypto_watch

Like pro.coinbase.com, but BEAM-flavoured
Elixir
31
star
4

mega-scraper

the mega scraper - scrape a website's content
JavaScript
23
star
5

twitter-oauth-login-in-nodejs

example repo for twitter oauth login in node.js
JavaScript
17
star
6

simple-telegram-message

send a telegram message to yourself, a friend or a channel with node.js
JavaScript
9
star
7

opening-hours-kata

Opening hours don't have to be so boring - A TDD & Refactoring Kata
9
star
8

timelapse-lambda

ffmpeg timelapse lambda with s3
JavaScript
8
star
9

christian-fei.github.io-pandoc

HTML
8
star
10

delay.js

delay javascript execution until element is in view
JavaScript
8
star
11

hacker-news-analytics

hacker news analytics
JavaScript
7
star
12

free-google-translate-with-puppeteer

translate any text for free
JavaScript
7
star
13

raspberry-pi-time-lapse

Shell
6
star
14

browserless-example

JavaScript
6
star
15

justchart

HTML
5
star
16

bull-dashboard

a simple bull queue dashboard
JavaScript
5
star
17

trello-recap

get a recap of your trello board 📋
JavaScript
4
star
18

email-newsletter-testing-by-example

Testing in Node.js by example using the SOLID principles
JavaScript
4
star
19

lambda-status

A Lambda that monitors and stores metrics of your web application
JavaScript
3
star
20

trello-replay

replay the actions on a trello board
JavaScript
3
star
21

hn-history

scrape hackernews every 20', save json and commit. show the diff on the web
JavaScript
3
star
22

husky-template

magic strings in javascript
JavaScript
3
star
23

devblog

yet another static site generator
JavaScript
3
star
24

open-weather-map-cli

☀️ unobtrusive weather report in the terminal ⚡️
JavaScript
3
star
25

twitter-oauth-by-example-in-nodejs

an example of twitter oauth in nodejs
JavaScript
3
star
26

angular-start

my starting point for angular projects
JavaScript
2
star
27

elixirsips-downloader

scripts to download elixirsips.com videos
JavaScript
2
star
28

angular-modest

Modest Angular module for handling nested REST resources.
JavaScript
2
star
29

telephone-directory

A simple phone book to learn a bit more about Heroku, Travis CI and test driven development with Jasmine.
JavaScript
2
star
30

Mouse-Follower-JS

JavaScript
2
star
31

pocket-sync

sync pocket items.
JavaScript
2
star
32

jenkins-stream-build

stream the build output on jenkins (or get a historic build output)
JavaScript
2
star
33

door-monitor-esp8266

C++
2
star
34

slack-waiter-bot

decide what to eat on slack
JavaScript
2
star
35

next-text

nextText is a small utility function to get the next letter from a partial string.
JavaScript
2
star
36

get-free-https-proxy

returns a list of free proxies (with host and port property) from sslproxies.org
JavaScript
2
star
37

opentalk.me

The real realtime chat - opentalk.me
CSS
2
star
38

raspberry-dotfiles

dotfiles for my raspberry pi
Shell
2
star
39

change-state

a stupid simple state container for your apps and tests
JavaScript
1
star
40

lambda-status-server

JavaScript
1
star
41

cypress-playground

JavaScript
1
star
42

notes-learning-ddd

notes on "Learning Domain-Driven Design" book
1
star
43

elixir_agent_spike

Elixir
1
star
44

slack-bot-example

JavaScript
1
star
45

elm-playground

HTML
1
star
46

get-google-oauth-authorization-code

1
star
47

christian-fei

1
star
48

led-server

JavaScript
1
star
49

p2p-workshop

JavaScript
1
star
50

fp-in-erlang-mooc

Erlang
1
star
51

garden

garden automation
JavaScript
1
star
52

payments

handle payments with stripe and with an aws lambda function
JavaScript
1
star
53

ansible-playground

JavaScript
1
star
54

eloquent-ruby-playground

Ruby
1
star
55

xpepperify

xpepperify your avatar!
Shell
1
star
56

vcgencmd-monitor

Monitor your Raspberry Pi through `vcgencmd` and a simple Web Interface
JavaScript
1
star
57

elixir_unix_pipe_example

Elixir
1
star
58

elixir_fridge

Elixir
1
star
59

hello_plug

Elixir
1
star
60

xpeppers-status

1
star
61

ping_pong

Elixir
1
star
62

harry-potter-kata-haskell

Haskell
1
star
63

echo_bot_elixir

another echo bot, this time in elixir
Elixir
1
star
64

phoenix_ws_playground

Elixir
1
star
65

sudoku-haskell

Haskell
1
star
66

simple-typewriter

typewriter for input elements
JavaScript
1
star
67

lucky-number-seven-kata

Elixir
1
star
68

desktop

pomodoro.cc desktop application
JavaScript
1
star
69

scraping_daringfireball_archive

scraping for number of words in the articles of https://daringfireball.net/archive/
Elixir
1
star
70

coinmarketcap-scraper

smart utility to create samples of daily market data for a given coin, start and end time 📈
JavaScript
1
star
71

json-to-csv-kata

CSV's don't have to be so boring
JavaScript
1
star
72

trellogram

trello board recap to your telegram or console
JavaScript
1
star
73

is-tx-confirmed

check if crypto transaction is confirmed
JavaScript
1
star
74

exo-train-kata

JavaScript
1
star
75

require-as-template-string

experiment in leveraging template strings to enable multiple requires
JavaScript
1
star
76

fp-rubiks

Haskell
1
star
77

elixir-playground

Elixir
1
star
78

mongo-current-op

display mongo current ops
JavaScript
1
star
79

ansible-pi

Shell
1
star
80

hello_ecto

Elixir
1
star
81

hn

A small, test-driven scraper for HackerNews
JavaScript
1
star