Starting with InstantSearch.js v4.46.0, every hits template provides anhtmlfunction that you can use as a tagged template. Usinghtmllets you safely provide templates as an HTML string. It works directly in the browser without a build step.
This htmlfunction should normally be called at the beginning of the return statement within the template.
In order to conditionally display HTML elements (ie: an <img> tag or a <svg> tag) within your hits template, you must call the htmlfunction again directly before each element in the conditional statement.
In the following example, we are using a ternary operator to conditionally display an <svg> circle or a cat <img> based on whether or not the brand is "Google".
instantsearch.widgets.hits({
container: '#hits',
templates: {
item(hit, { html, components }) {
return html`<article>
<h2>${hit.name}</h2>
<p>${hit.price}</p>
${hit.brand === 'Google'
? html`<svg>
<circle fill="red" cx="20" cy="20" r="20" />
</svg>`
: html`<img src="https://loremflickr.com/120/120" />`}
</article>`;
},
},
}),
If we do not include the additional htmlfunction calls before each element, the HTML element will be displayed as a text string (ie: "<img src="https://loremflickr.com/120/120" />") instead of an actual image.
This Code Sandbox provides a working example in InstantSearch.js.