2017-08-04 46 views
1

我希望能夠根據從搜索中檢索到的值更改模板。我想改變變量的內容是這樣的:使用InstantSearch.js在運行時選擇不同的模板

search.addWidget(
    instantsearch.widgets.hits({ 
    container: '#hits', 
    hitsPerPage: 12, 
    templates: { 
     empty: noResultsTemplate, 
     item: hitTemplate 
    }, 
    transformData: function (hit) { 
     if (hit.myVariable == true) { 
      this.templates.item = otherTemplateVariable; 
     } 
     return hit; 
    } 
    }) 
); 

但我得到一個錯誤:'Unable to get property 'templates' of undefined or null reference'

回答

0

的問題似乎是,你引用this和指向功能transformData不具備模板屬性,嘗試提取您的對象來訪問它:

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; 
    } 
    }; 

search.addWidget(
    instantsearch.widgets.hits(data) 
); 
+0

試過但沒有使用新分配的模板。一旦在'模板'中聲明,它將使用那個:(通過從'模板'列表中刪除'項目'並將其添加到else語句來證實這一點,並且兩者都不會使用。 – user0187409