Trying to add search to this website

2022/08/20

Categories: web Tags: web

I’m interested in adding some search functionality to this website. Unfortunately, it looks like adding search to a blogdown site is something that is more theme specific. Since my theme does not implement search, I’m on my own.

It looks like there are two ways to add search.

  1. Export the problem to a proper search engine like Google.
  2. Build an on-site search engine using lunr.js or something similar.

I use Hugo to maintain this website. The Hugo docs show some examples of how to add custom site search, but none of these looked like something I would like to implement and maintain.

I ended up hacking together a search page that links to Google, so I chose to implement method 1. The solution is not very complex, and the whole js code is just one function. I follow [this post](https://digitaldrummerj.me/hugo-integrate-google-search/ " ") closely.

<script language="Javascript" type="text/javascript">
function google_search() {
    var query = document.getElementById('google-search').value;
    window.open(
    'https://www.google.com/search?q=' + query + '+site:' + '{{ .Site.BaseURL | absLangURL }}'
    );
}
</script>

{{define "main" }}
{{ end }}

<form id="search" onsubmit="google_search(); return false;">
    <div class="form-group form-group-lg">
        <input
            type="text"
            class="form-control"
            id="google-search"
            placeholder="Enter search term and hit enter"
        />
    </div>
</form>

Give the site search a try and let me know if there is a better way to rely on Google to solve this problem. I think the “go to a different page just to search” solution is inelegant, but I never found a way to put this code properly in the header or footer of my webpages. DuckDuckGo does offer a search widget that fits in the header or footer of this blog, but I removed it because I thought it looked ugly. -__-

Hopefully, the search bar will prevent me from writing the same blog post multiple times.