In order to add a banner image to your search results the first thing you'll want to do is to determine where the image you want to display can be found. You can use any hosted image link you want to include the image in your banner.
One of the easiest ways to place an image in your banner is to use an image hosting CDN and then use that image URL in your rule. There's many choices for 3rd party image hosting CDN's, Cloudflare is one of the most popular. Once you have the image you would like hosted on a CDN and you have the URL then you can build the rule for your banner.
Following this guide the first step is to go to the rules page of the Algolia dashboard for the index you would like the rule to be active on. Select Create your first rule or New rule. In the dropdown, click on the Manual Editor option. In the Condition(s) section, keep Query toggled on, select Contains in the dropdown, and enter the query you would like to trigger the rule in the input field. For this example I've created two conditions, query contains "computer" or query contains "laptop".
In the Consequence(s) section:
- Click the Add consequence button and select Return Custom Data.
- In the input field that appears, add the data to return when the user query matches the Rule. For this example I've added two values "banner_image" and "banner_text". I've included the image URL thats hosted on our CDN for "banner_image". You can think of this custom data as variables that you will access later from the front end.
.
Once you have added your custom data click save at the bottom of the page. Now that your Rule is ready, you can add a banner in your search UI when the userData
property is present in the API response. Here’s what it could look like with InstantSearch:
instantsearch.widgets.queryRuleCustomData({
container: '#banner',
templates: {
default: `
{{#items}}
<img src={{banner_image}} />
<h2>{{banner_text}}</h2>
{{/items}}
`,
},
}),
This code is accessing our hosted image url we added in "banner_image" to the HTML <img> src dynamically. This tells the front end to render an HTML img element with a src of "https://cdn-demo.algolia.com/bestbuy-0118/5588602_sb.jpg". After that we have our banner text in an h2 element, but you can customize the template to fit your needs.
Now anytime a user query contains "computer" or "laptop", the banner will be displayed with our image and text. Here's a CodeSandBox showing the rule in action.