Instantsearch.js - If else

I have a custom template where i want to use an if statement, but i am not quite sure how to do it.
I have a big template block, within this block i want to show an image if the user is premium or not. So something like this

templates: {
                item: `
              BIG BLOCK
               .....
              if {{ user.isPremium }} === true 
                   show image
              ....
              BIG BLOCK

Does anyone have a tip for me show i would make a simple if statement within the item object?

Hi there, you would do it this way:

const image = user.isPremium ? '<img src="https://...." />' : '';
// then, use the image variable this way:

templates: {
item: `
BIG BLOCK

${image}

BIG BLOCK

Please see how to use template strings here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

1 Like

Thanks for your reply.
But where exactly would i define const image?

Because

search.addWidget(
        instantsearch.widgets.hits({
       .....

Is of course just the object. Where do i have access to the isPremium var from the Algolia record?

Here i am getting undefined / i don’t have access to isPremium

let search = instantsearch({
    indexName: 'Partner',
    searchClient,
});

console.log(isPremium);

search.addWidget(
    instantsearch.widgets.hits({
  .....

Per your original question, item can be a string (as per examples above) OR a function:

instantsearch.widgets.hits({
  // ...
  templates: {
    item(hit) {
      const image = hit.isPremium ? '<img src="https://...." />' : '';
      return `
        BIG BLOCK
        …
        ${image}
        …
        BIG BLOCK
      `;
    },
  },
});

My example of course assumes isPremium is defined in the Algolia record being returned.