manastech / middleman-search

LunrJS-based search for Middleman
MIT License
58 stars 31 forks source link

How to use middleman-search for a search box? #11

Closed Jeeppler closed 8 years ago

Jeeppler commented 8 years ago

Does middleman-search provide any tag or function which can be used for a search box?

spalladino commented 8 years ago

Nothing out of the box, but feel free to adapt the code we use in our website for searching. More info in this blogpost.

Jeeppler commented 8 years ago

thank you for your reply. One thing is pretty unclear for me. Where do you get your .json file for lunr?

spalladino commented 8 years ago

That's the index file autogenerated by the extension once you activate it. It defaults to search.json in the gem, though it's index.json in the example.

spalladino commented 8 years ago

@Jeeppler let me know if you've managed to solve this, so we close the issue

Jeeppler commented 8 years ago

I was able to solve this. The code you provided to me works fine.

The only thing is you use the lodash library in the following code snipped:

var result = _(lunrIndex.search(request.term)).take(50).pluck('ref').map(function(ref) {
  return lunrData.docs[ref];
}).value();

took me a while to figure out that the underscore belongs to the lodash library. Furthermore you use lodash v. 3 whereas the newest version is 4. In the version for the pluck method was removed.

I did not want to learn another library and decided to use pure JavaScript for that part:

var max_search_entries = 50;

var result = []; //initialize empty array

lunrIndex.search(request.term).forEach( function (item, index) {
  if ( index < max_search_entries ) {
    result.push(lunrData.docs[item.ref]);
  }
});

The code does exactly the same.

Jeeppler commented 8 years ago

Since this is an issue and therefor hard to find I would like to see the source code, the blogpost and your website link in the repo README.md.

Thanks for your help.

macandcheese commented 7 years ago

@Jeeppler thank you, the replacement code you posted worked!

matiasgarciaisaia commented 7 years ago

@macandcheese would you mind sending a PR with a proposal for adding the explanation to the README.md? Having been in the need so recently, I think your input for that would be really valuable :)

macandcheese commented 7 years ago

@matiasgarciaisaia Hi - unfortunately I can't add much more as I just used the code above!

The error in console is "Uncaught ReferenceError: _ is not defined", and the code above from @Jeeppler solves for that as it doesn't require anything from lodash.