Functions within Hit Template

Hi,

I’m attempting to add 2 functions to a hits template… (1) Decide what price to show based on the value of several attributes in index. (2) Then, depending on which price is selected, another function to format that price.

The solution in this post shows how to add a function, but it returns the entire template.

The ideal solution would be the hit template below, where I can replace {{ Pricing }} using the 2 functions (1) determine what price to display - based on multiple attributes in index - and (2) the format of that price (rounded, with dollar sign, etc.).

What is the best way to accomplish this?

 templates: {
    item:
`
<div class="hit-header-block">
  <img class="hit-thumbnail" src="//logo.clearbit.com/hubspot.com?size=80">
  <p class="hit-title-secondary">{{ Vendor }}</p>
  <h5 class="hit-title-primary">{{ Card Name }}</h5>
</div>
<div class="hit-pricing-block year">
  <h5 class="hit-price">{{ Pricing }}</h5>
</div>
`}

Attempt using variables, but doesn’t work… doesn’t update attribute values.

var otherOther = 
`<div class="hit-header-block">
  <img class="hit-thumbnail" src="//logo.clearbit.com/hubspot.com?size=80">
  <p class="hit-title-secondary">{{ Vendor }}</p>
  <h5 class="hit-title-primary">{{ Card Name }}</h5>
</div>
<div class="hit-pricing-block year">
  <h5 class="hit-price">{{ Pricing - Other - Paid Yearly }}</h5>
</div>
<div class="hit-pricing-block month">
  <h5 class="hit-price">{{ Pricing - Other - Paid Monthly }}</h5>
</div>`

instantsearch.widgets.hits({
    container: '#hits',
    templates: {
        item:function(data) {
          if(data['Pricing - Other - Paid Yearly']) {
            if(data['Pricing - Other - Paid Monthly']) {
              return otherOther
            } else {
              return otherPrice
            }
          } else {
            if(data['Pricing - Other - Paid Monthly']) {
              return priceOther
            } else {
              return pricePrice
            }
          }
        }
      }
  }),

Hi @dom,

If you need to update the attribute values in each record before display, have you considered the transformItems option. This way the record has updated attribute vales before going to the template.

Here are the docs: https://www.algolia.com/doc/api-reference/widgets/hits/js/#widget-param-transformitems.

Let us know more detail or provide a sandbox if we can help further - we have templates with much of the boilerplate started here: https://github.com/algolia/create-instantsearch-app#previews

Thank you @ajay.david ! Transform items worked great for my use case.

Code for reference:

instantsearch.widgets.hits({
   container: '#hits',
   transformItems(items) {
     return items.map(item => ({
        ...item,
        priceYear: setPriceYear(item),
        priceMonth: setPriceMonth(item),
    }));
    },
   templates: {
       item:
//...
1 Like