Instantsearch hits add headers

In my app the hits widget needs to display data in a tabular format. I’m looking to see if how I can have headers at the top of my three columns where the hits data is displayed.

What does Algolia have for adding column headers inside a hits widget?

https://jsfiddle.net/jandk4014/amv01e4w/151/

search.addWidget(
  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      item: function(item) {
        return `
          	<div class="row">
              <div class="result-code col-md-3 col-sm-4 col-xs-4">
              	<a href="https://www.lyntron.com/${item.url}">${item._highlightResult.code.value}</a>
              </div>
              <div class="result-description col-md-8 col-sm-7 col-xs-7">
              	${item.description}
              </div>
              <div class="result-available col-md-1 col-sm-1 col-xs-1">
              	${item.quantityAvailable.toLocaleString()}
              </div>
            </div>
          `;
      }
    },
    cssClasses: {
        root: 'row',
  		item: 'col-lg-12 col-md-12 col-sm-12'
    }
  })
);

for a table it’s better to use the allItems template, which requires you to do the looping yourself (but it’s fairly straightforward, just map over items).

Does that help you?

@haroen

That gets me closer I’d say. I found this example online for usage. However, I can’t seem to understand how to use a header for the items? Is there a class called 'ais-hits-header'?

If you’re using the allItems template, you can customise the classes however you want. An example using the template syntax:

allItems: `
  <table>
    <thead>
      <tr>
        <th>name</th>
        <th>description</th>
      </tr>
    </thead>
    <tbody>
    {{#hits}}
      <tr>
        <td>{{ name }}</td>
        <td>{{ description }}</td>
      </tr>
    {{/hits}}
    </tbody>
  </table>
`

It’s also possible to create such a syntax with the functionn form, where you’d loop yourself, rather than letting Hogan do that.

1 Like

@haroen

That did it exactly! Thanks for the example.

1 Like

@haroen,

Is it possible to switch the allItems template at runtime? For example let’s say that depending on the expected results I want to showcase a different and subsequently have different columns for

How can I switch the template out at runtime?

This follow-up question relates to: InstantSearch return an unique allItems template at runtime