개발(Web)/VCS

[Git/GitHub] Jekyll 기반의 GitHub Page 생성(5) - lunr.js를 이용한 Search 기능 추가 (2)

shinyelee 2021. 3. 14. 23:08

lunr.js

 

Jekyll 기반의 GitHub Page 생성(5) - lunr.js를 이용한 Search 기능 추가

Jekyll 기반의 GitHub Page 생성은 여러 절로 구성되어 있습니다. Jekyll 기반의 GitHub Page 생성(1) - 환경설정 Jekyll 기반의 GitHub Page 생성(2) - 블로그 수정 & Publishing Jekyll 기반의 GitHub Page 생성(3) - 웹 폰트

moon9342.github.io

강사님 블로그에서 밑줄친 부분을 클릭하면 새 창이 뜨는데 알못 입장에선 조금 당황스러울 수 있음
자동으로 다운로드 되는 게 아니기 때문에 우클릭 후 다른 이름으로 저장...
저장한 후
js 폴더 밑에 붙여넣으면 됨


search.js

js 폴더 하위에 search.js 생성
search.js에 아래 코드 복붙

(function() {
    function displaySearchResults(results, store) {
        var searchResults = document.getElementById('search-results');

        if (results.length) { // Are there any results?
            var appendString = '';

            for (var i = 0; i < results.length; i++) {  // Iterate over the results
                var item = store[results[i].ref];
                appendString += '<li><a href="' + item.url + '"><h6>' + item.title + '</h6></a>';
                appendString += '<p>' + item.content.substring(0, 150) + '...</p></li>';
            }

            searchResults.innerHTML = appendString;
        } else {
            searchResults.innerHTML = '<li>검색 결과가 없습니다.</li>';
        }
    }

    function getQueryVariable(variable) {
        var query = window.location.search.substring(1);
        var vars = query.split('&');

        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split('=');

            if (pair[0] === variable) {
                return decodeURIComponent(pair[1].replace(/\+/g, '%20'));
            }
        }
    }

    function trimmerEnKo(token) {
        return token
            .replace(/^[^\w가-힣]+/, '')
            .replace(/[^\w가-힣]+$/, '');
    };

    var searchTerm = getQueryVariable('query');

    if (searchTerm) {
        document.getElementById('search-box').setAttribute("value", searchTerm);

        // Initalize lunr with the fields it will be searching on. I've given title
        // a boost of 10 to indicate matches on this field are more important.
        var idx = lunr(function () {
            this.pipeline.reset();
            this.pipeline.add(
                trimmerEnKo,
                lunr.stopWordFilter,
                lunr.stemmer
            );
            this.field('id');
            this.field('title', { boost: 10 });
            this.field('author');
            this.field('category');
            this.field('content');
        });

        for (var key in window.store) { // Add the data to lunr
            idx.add({
                'id': key,
                'title': window.store[key].title,
                'author': window.store[key].author,
                'category': window.store[key].category,
                'content': window.store[key].content
            });

            var results = idx.search(searchTerm); // Get lunr to perform a search
            displaySearchResults(results, window.store); // We'll write this in the next section
        }
    }
})();

잘따라왔고, 깃허브에 제대로 푸시했다면
제목/목차가 해당 키워드를 포함하는 경우
검색에 걸리게 됨

 

출처 : 

 

Jekyll 기반의 GitHub Page 생성(5) - lunr.js를 이용한 Search 기능 추가

Jekyll 기반의 GitHub Page 생성은 여러 절로 구성되어 있습니다. Jekyll 기반의 GitHub Page 생성(1) - 환경설정 Jekyll 기반의 GitHub Page 생성(2) - 블로그 수정 & Publishing Jekyll 기반의 GitHub Page 생성(3) - 웹 폰트

moon9342.github.io

반응형