Using Handlebars.js To Display Results From Solr- A Primer

Handlebars provides the power necessary to let you build semantic templates effectively with no frustration.

Handlebars.js is a really great way to render search results from Solr.

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>

Article written by

Fergus McDowall
Senior Consultant at Comperio. Dedicated emacs user.

1 response to: «Using Handlebars.js To Display Results From Solr- A Primer»

  1. July 26, 2013 at 17:42 | Permalink

    Hi Fergus,
    I tried your code, It’s not working.

    Thanks



Leave a response





XHTML: These tags are allowed: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">

Powered by sweetCaptcha


OSLO

Comperio AS
Øvre Slottsgate 27
NO-0157 Oslo,
Norway
+47 22 33 71 00
View map

STOCKHOLM

Search Provider Sverige AB
Gamla Brogatan 34
SE-11 120 Stockholm
Sweden
+46 8-21 49 00
View map

LONDON

Comperio Search Ltd
64 Great Eastern Street
London EC2A 3QR
United Kingdom
+44 207 749 9131
View map