Edit result templates widgets.hits

Hi, this is the script I’m using with javascript:

 search.addWidget(instantsearch.widgets.hits({
        container: '#results',
        templates: {
            empty: '<p class="info">No results.</p>',
            item: `
            <div class="hit-data">
            {{#helpers.highlight}}{ "attribute": "published_at" }{{/helpers.highlight}}
            </div>
            `,
        },
    }));

I would like to format date published_at before it is printed.
In this way: published_at.toDateString();

Something like this:

<div class="hit-data">
{{#helpers.highlight}}{ "attribute": "published_at.toDateString()" }{{/helpers.highlight}}
</div>

How can I solve it?

You can use the transformItems option to format published_at before passing the value to the templates. However, using the highlight helper doesn’t make sense for this value. It’s not meant to be highlighted because Algolia likely doesn’t return a highlighted value for published_at.

Something like this should work:

search.addWidget(
  instantsearch.widgets.hits({
    container: "#hits",
    transformItems: items =>
      items.map(item => ({ ...item, date: item.published_at.toDateString() })),
    templates: {
      item: `
<div class="hit-data">
  {{date}}
</div>
`
    }
  })
);

Hi, thanks for the quick reply.
I had seen this possibility on the documentation, but I had failed to implement it.
I still have a problem:

search.addWidget(instantsearch.widgets.hits({
    container: "#results",
    transformItems: items => items.map(item => ({ ...item,
        date: item.published_at.toDateString()
    })),
    templates: {
        item: `
      <div class="hit-data">
      {{date}}
      </div>
      `
    }
}));

From console:
Uncaught (in promise) TypeError: item.published_at.toDateString is not a function

It’s likely because published_at is a timestamp. You need to convert it to a Date before using toDateString():

new Date(published_at).toDateString()
1 Like