Using Handlebars.js To Display Results From Solr- A Primer
Handlebars.js has become the defacto standard for templating in JavaScript, filling the void left from the abandonment and non-replacement of the jQuery template project. Handlebars.js is an implementation of the mighty platform-independant mustache project
JavaScript templating makes it a lot easier to implement cool interface functionality on your search result page such as responsive design, autoscrolling and more. Handlebars make JS templating a cinch.
You get the benefit of Handlebars.js on webpages that have a lot of repeating code such as lists, search-results and libraries.
In order to see Solr and Handlebars.js in action click here or copy and paste the code below into an empty .html file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<b>Handlebars.js and Solr Demo</b><br> Type in something reutersey and click the <b>search</b> button!<br> <input id="searchterm" /> <button id="search">search</button> <div id="rs"></div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0.beta6/handlebars.min.js"></script> <script id="hit-template" type="text/x-handlebars-template"> <div class="entry"> <b>{{title}}</b><br> {{text}} </div> </script> <script type='text/javascript'> var hitTemplate = Handlebars.compile($("#hit-template").html()); $("#search").click(function(){ $("#rs").empty(); $.getJSON("http://evolvingweb.ca/solr/reuters/select/?q=" + $("#searchterm").val() + "&wt=json&json.wrf=?&indent=true", function(result){ for (var i = 0; i < result.response.docs.length; i++) { $("#rs").append(hitTemplate({title: result.response.docs[i].title, text: result.response.docs[i].text})); } }); }); </script> |
Hi Fergus,
I tried your code, It’s not working.
Thanks
hi Fergus, thanks for posting this. works great and is lightening fast. Am trying to work out how to integrate customised bias/weighting settings to be appended to the solr query in a multilingual environment….if you have had any experience of this, can you post an update if you have time?
Also..I notice a few odd behavioural things, such as when you have facets applied and then type into the search box, it seems to reset the chosen facets. that a jquery issue or handlebars issue?
anyway, thanks again for posting.
gus
Hi Gus
This code is now a few years old and is probably due for a revamp. Its quite possible that there is now some mismatch between versions of Solr/JS/moustache which make facets and filters not work as intended.
For the relevancy stuff- the solr wiki is quite good: https://wiki.apache.org/solr/SolrRelevancyFAQ
Ping me on twitter (@fergiemcdowall) if you need any more help :)
F