customize Algolia instantSearch.js addWidget function

577 views Asked by At

I want to edit the container of Hits , based on the results returned by Algolia, assume the following: hits-container

<div id="hits">
    <div class="col-md-2">{{ id }}</div>
    <div class="col-md-2">{{ user }}</div>
    <div class="col-md-2">{{ email }}</div>
    <div class="col-md-2">{{ date }}</div>

    <a href="/orders/{{id}}/edit" class="btn" >
        <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>
    </a>
</div>

addWidget function :

<script type="text/javascript">
search.addWidget(
    instantsearch.widgets.hits({
        container: '#hits-container',
        templates: {
            item: $('#hits').html(),
            empty: 'No Orders',
        }
    })
);
</script>

suppose I want to disable the edit link if the date is less than the current date, addWidget will display all the results returned by Algolia inside this container , now I want to apply some logic before displaying the results. any suggestions ?

1

There are 1 answers

0
Marie On BEST ANSWER

InstantSearch.js widget templates can be defined either as a Mustache string or as a function receiving the widget data and returning a string.

This function could contain the logic about disabling your edit link. Something like:

templates: {
  item: function(data) {
    let className = "";
    if (data.rating < 4) {
      className = "bad-rating";
    }
    return (
      "<div" +
      ' class="' +
      className +
      '">' +
      data._highlightResult.title.value +
      "</div>"
    );
  }
}

Here is a complete jsfiddle showcasing it.