Choose different Template at Run Time with InstantSearch.js

with instantSearch I need to show different tamplates according to a variable retrieved from the search. On the web I found the following code:

var data = {
 container: '#hits',
 hitsPerPage: 12,
 templates: {
    empty: noResultsTemplate,
    item: hitTemplate
 transformData: function (hit) {
    if (hit.myVariable == true) {
      //access the templates attribute
      data.templates.item = otherTemplateVariable;
    return hit;


The problem is that it doesn’t use the new assigned template (otherTemplateVariable) but always the predefined (hitTemplate).
Any idea?

Hello @nicola.vigano

You should do your if condition into the template data itself. You can access to the hit object in the template itself.

For example:

templates: {
  item: (hit) => {
    if (hit.myVariable) { 
      return ... 
    } else {
      return ...

You can read more about hit templating options:

Feel free to ask anything else.

Cheers, Maxime.

@iam4x - I believe what the original poster is asking is how to change the underlying template where the hits object is being rendered at. You solution should just modify the items iteratively. Where they’re asking about changing the layout of the entire template.

I’m also dealing with that same issue with this post: InstantSearch return an unique allItems template at runtime