Skip to main content
Signature
components.Snippet({
  attribute: string,
  hit: object,
  // Optional parameters
  highlightedTagName?: string,
  nonHighlightedTagName?: string,
  separator?: string,
  cssClasses?: object,
});

About this widget

The snippet function returns attributes in your search results in a shorter form (a snippet). Snippeted attributes are also highlighted. This function uses Algolia’s snippeting feature in combination with the hits or infiniteHits widgets. To determine which attributes should be snippeted, first set them from the Algolia dashboard, the CLI, or with the API (using the attributesToSnippet parameter):
JavaScript
search.addWidgets([
  configure({
    attributesToSnippet: ["description"],
  }),
]);
With attributesToSnippet, you can also set the snippet’s size to a specific number of words (it defaults to 10). For example, attributesToSnippet: ['description:5'].

Examples

JavaScript
hits({
  container: "#hits",
  templates: {
    item(hit, { html, components }) {
      return html`
        <h2>${hit.name}</h2>
        <p>${components.Snippet({ attribute: "description", hit })}</p>
      `;
    },
  },
});

Options

attribute
string
required
The attribute of the record to snippet. For deeply nested objects, specify a dot-separated value like actor.bio.
JavaScript
components.Snippet({
  // ...
  attribute: "description.full",
});
hit
object
required
Original hit object provided to the function. The value is already bound to the function inside a string template, so you don’t have to provide it. For this to work, the provided object must have a _snippetResult[attribute].value property.
JavaScript
components.Snippet({
  // ...
  hit: item,
});
highlightedTagName
string
default:"mark"
The name of the HTML element to wrap the snippeted parts of the string.
JavaScript
components.Snippet({
  // ...
  highlightedTagName: "em",
});
nonHighlightedTagName
string
default:"span"
The HTML element that wraps the non-highlighted parts of the string.
JavaScript
components.Snippet({
  // ...
  nonHighlightedTagName: "div",
});
separator
string
default:", "
The character between each item when the attribute to highlight is an array.
JavaScript
components.Snippet({
  // ...
  separator: " - ",
});
cssClasses
object
default:"{}"
The CSS classes you can override:
  • root. The component’s root element.
  • highlighted. The highlighted parts.
  • nonHighlighted. The non-highlighted parts.
  • separator. The separator elements between highlighted parts.
JavaScript
components.Snippet({
  // ...
  cssClasses: {
    root: "MyCustomSnippet",
    highlighted: ["MyCustomSnippetPart", "MyCustomSnippetPart--subclass"],
  },
});

HTML output

HTML
<span>This is the <mark class="ais-Snippet-highlighted">highlighted text</mark></span>
I