Create Autocomplete template

Attributes

The following data-* attributes are required by the library to handle attributions (click events) for products/keywords/history items rendered in the autocomplete result:

data-ns-hit

This attribute should be used on clickable keyword, product, history list elements. This attribute handles submit keyword/history as search, redirect to product, analytics (if enabled) request.

Encode HTML content

This is specific to cases where no template language like liquid/handlebars is used and the content is rendered using plain HTML.

Make sure to HTML encode content passed to this attribute. Bacause JSON.stringify may produce result that can't be directly used in HTML especially when the content includes special characters.

For example, consider the below example

{
  "keyword": "new year's eve",
  "_highlight": { "keyword": "new year's eve" }
}

can be encoded as

{&quot;keyword&quot;:&quot;year's eve&quot;,&quot;_highlight&quot;:{&quot;keyword&quot;:&quot;<strong>year</strong>'s eve&quot;}}

Following table shows value for this attribute depending on the rendering context.

Context
Value

keyword

value from response.data.search.keywords

Code example:

const { keywords } = response.data.search
const contentToRender = keywords.map(keyword => 
    `
    <div data-ns-hit="${JSON.stringify(keyword)}" ....>
        ....
        ....
    </div>
    `
)

Value example:

{
    "keyword": "midi dresses",
    "_highlight": { "keyword": "midi <strong>dress</strong>es" }
}

product

productId and url from response.data.search.products.hits

Code example:

const { hits } = response.data.search.products
const contentToRender = hits.map(({ productId, url }) => 
    `
    <div data-ns-hit="${JSON.stringify({ productId, url })}" ....>
        ....
        ....
    </div>
    `
)

Value example:

{
    "productId": 123456,
    "url": "https://example.com/products/example-product-handle"
}

history

historyEnabled & historySize config. Refer Initialization

data-ns-remove-history

This attribute should be used to delete history entries in the autocomplete

To make an element delete a single history entry when clicked, add data-ns-remove-history={hit.item} to an element. In order to delete all history entries, add data-ns-remove-history="all" to clear button.

Starter templates

This section provides links to default startup templates for different rendering frameworks. These templates can be copied and customized as needed.

Handlebars, Mustache, Liquid, React/Preact (HTML)

Mustache helpers

Mustache is based on logic-less templates which can be enhanced with helpers, e.g toJson, imagePlaceholder, showListPrice in example template.

import { fromMustacheTemplate } from '@nosto/autocomplete/mustache'

fromMustacheTemplate(template, {
    helpers: {
        toJson: function () {
            return JSON.stringify(this)
        },
    },
})

Last updated

Was this helpful?