InstantSearch v3 / connectHits / js tpl

In my html, i have a js tpl :

<script type="text/html" id="hit-template">
  <article class="" itemscope="" itemtype="http://schema.org/Product">
      {{ name }}
  </article>
</script>

I create a connecHits; how can i render hit with my hit-template ?

const makeHits = instantsearch.connectors.connectHits(function renderHits(
  renderParams,
  isFirstRendering
) {
  var container = renderParams.widgetParams.container;
  if (!isFirstRendering) {
    const optionsHTML = items.map(function(item) {
      return document.getElementById("hit-template").innerHTML;
    });
    $(container).html(optionsHTML);
  }
});

Hey there,

Templates aren’t available when you are using a connector. The way to go instead is to either make DOM elements from scratch on every render (with document.createElement etc.).

If you imported instantsearch.js via npm (not via CDN), then it comes with Hogan.js, which allows you to compile these templates yourself. The code we use for that looks like this:

Make sure to add hogan.js (the same version as used in InstantSearch.js) to your package.json if you do so; and import like this: import hogan from 'hogan.js';

I m not using npm, so i have to add hogan.js;
thx fr your help (you should tell it in your doc)
My code is working now :

$(document).ready(function() {
  var makeHits = instantsearch.connectors.connectHits(function renderHits(
    renderParams,
    isFirstRendering
  ) {
    var container = renderParams.widgetParams.container;
    if (!isFirstRendering) {
      var items = renderParams.results.hits;
      var tpl = Hogan.compile(renderParams.widgetParams.templates.item);
      var optionsHTML = items
        .map(function(item) {
          // console.log(item);
          return tpl.render(item);
        })
        .join("");
      $(container).html(optionsHTML);
    }
  });

  const client = algoliasearch(al_applicationID, al_apiKey);
  const search = instantsearch({
    indexName: al_indexName,
    searchClient: client,
    routing: true,
    searchFunction(helper) {
      helper.search();
    }
  });
  //////////
  search.addWidget(
    makeHits({
      container: "#wrapper",
      templates: {
        item: document.getElementById("hit-template").innerHTML
      }
    })
  );

  //////////
  search.start();
});
1 Like