【问题标题】:Choose different Template at Run Time with InstantSearch.js使用 InstantSearch.js 在运行时选择不同的模板
【发布时间】:2018-01-12 20:17:15
【问题描述】:

我希望能够根据从搜索中检索到的值更改模板。我想过像这样更改变量内容:

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'

【问题讨论】:

    标签: javascript jquery instantsearch.js


    【解决方案1】:

    问题似乎是您正在引用 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)
    );
    

    【讨论】:

    • 试过了,但没有使用新分配的模板。一旦在“模板”中声明,它将使用那个:(。通过从“模板”列表中删除“项目”并将其添加到 else 语句来证实这一点,并且两者都不会使用。
    猜你喜欢
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多