rzschoch
rzschoch

Reputation: 358

Render a headline when search results are displayed

I didn’t find a way to output a headline (Search results:) in front of the search results that is only visible when results are displayed.

It wouldn’t be a problem to have it every time (part of the hit item template) but I don’t need one if the empty results template is displayed.

What would be a nice solution?

Here is my current hits widget configuration:

this.search.addWidget(
  this.algoliaInstantSearch.widgets.hits({
    container: '.js-algolia-hits',
    escapeHits: true,
    templates: {
      item: document.querySelector('.js-algolia-hit-item-template').innerHTML,
      empty: window.algoliaEmptyResultsText
    },
    cssClasses: {
      root: 'c-search__hits-list',
      empty: 'c-search__hits-empty',
      item: 'c-search__hits-list-item'
    }
  })
);

Upvotes: 0

Views: 139

Answers (1)

maxt
maxt

Reputation: 141

You can use the allItems template option to have the total control of the rendering of the hits.

search.addWidget(
  instantsearch.widgets.hits({
    container: document.querySelector("#products"),
    templates: {
      allItems: function({ hits }) {
        // No results message
        if (hits.length === 0) return "";

        const hitsMarkup = hits
          .map(
            hit =>
              `<div class="ais-hits--item">${
                hit._highlightResult.name.value
              }</div>`
          )
          .join("");

        return `
          <div>
            <h1>Search Results:</h1>
            <div class="ais-hits--container">${hitsMarkup}</div>
          </div>
        `;
      }
    }
  })
);

You can see the result here: https://codesandbox.io/s/8zxxvo84wl

Upvotes: 1

Related Questions