Result templates
Result templates
Result templates determine the format of the individual query results in a search interface.
In Headless, a ResultTemplate
is an object that specifies the content of a template as well as a list of conditions to fulfill for that template to be selected for any given result.
Example
import { ResultTemplate, Result } from "@coveo/headless";
import React from "React"
const myResultTemplate: ResultTemplate = {
content: (result: Result) => (<div>{result.title}</div>),
conditions: [(result: Result) => {
return !!result.title;
}]
}
Headless lets you create and manage templates with its ResultTemplatesManager
class.
To use the ResultTemplatesManager
, you must instantiate it and register result templates before a query is executed.
When you render results, you can then call on the manager to select the most appropriate template for that result.
The following example code shows a basic use case of the ResultTemplatesManager
.
import { buildResultTemplatesManager,
ResultTemplatesManager,
Result,
ResultTemplatesHelpers } from "@coveo/headless";
import { headlessEngine } from "../Engine";
// ...
export default class ResultList {
// ...
private headlessResultTemplatesManager: ResultTemplatesManager;
// ...
constructor(props: any) {
// ...
this.headlessResultTemplatesManager =
buildResultTemplatesManager(headlessEngine);
this.headlessResultTemplatesManager.registerTemplates(
{
conditions: [],
content: (result: Result) => (
<li>
<h4>{result.title}</h4>
<p>{result.excerpt}</p>
</li>
)
},
{
conditions: [
ResultTemplatesHelpers.fieldMustMatch("source", ["Techzample"])],
content: (result: Result) => (
<li>
<h4>Techzample: {result.title}</h4>
<p>{result.excerpt}</p>
</li>
),
priority: 1
}
);
// ...
}
// ...
render() {
return (
<ul>
{this.state.results.map((result: Result) => {
const template =
this.headlessResultTemplatesManager.selectTemplate(result);
return template(result);
})}
</ul>
);
}
}
Instantiates a new ResultTemplatesManager . |
|
Registers templates on your ResultTemplatesManager .
You can pass multiple templates as separate parameters, or call registerTemplates multiple times. |
|
Results will always satisfy this template’s conditions because there are none, making this the default template. | |
Headless offers result template helpers to make it easier to define conditions. See the code: src/features/result-templates/result-templates-helpers.ts. | |
Sets the priority of the result template. If multiple templates' conditions are satisfied by a given result, the template with the highest priority will be selected. If multiple templates have equal priority, the first template registered will win out. | |
Selects the most appropriate result template for the given result. |