Skip to content

Working With Templates

To allow for complete control over the look-and-feel of your search results and ad containers, we use template functions. All that is needed is to pass in a user-defined template function to <searchcraft-search-results> (for search results) and the SearchcraftConfig (for ad containers).

First, define the template function.

// This is a user-defined type. It corresponds to your search index's fields.
type SearchResultIndexFields = {
link: string;
title: string;
description: string;
image_url: string;
image_alt: string;
};
export const searchResultTemplate: SearchResultTemplate<
SearchResultIndexFields
> = (data, index, { html }) => html`
<a href="${data.link}" target="_blank" rel="noreferrer">
<div>
<h2>${data.title}</h3>
<p>${data.description}</p>
</div>
<img class="searchcraft-search-result-image" src="${data.image_url}" alt="${data.image_alt}" />
</a>
`;

Next, we pass the template to the <searchcraft-search-results> component. How this is done depends on what framework you are using.

main.ts
document.addEventListener('DOMContentLoaded', () => {
const searchResults = document.querySelector('searchcraft-search-results');
searchResults.template = mySearchResultsTemplate;
});
main.ts
import type { CustomAdTemplate, Searchcraft } from '@searchcraft/<your-sdk-framework>';
export const customAdTemplate: CustomAdTemplate = (data, { html }) => html`
<div class="searchcarft-custom-ad" id="${data.adContainerId}">
Custom ad for <strong>${data.searchTerm}</strong>
</div>
`;
// Pass in the template to the Searchcraft instance
const searchcraft = new Searchcraft({
...
customAdTemplate: customAdTemplate,
});

For more in-depth information on Custom Ads, see the Custom Ads page.