【问题标题】:Algolia template if no hits are returned如果没有返回命中,则 Algolia 模板
【发布时间】:2016-07-08 18:07:05
【问题描述】:

我已经基于https://www.algolia.com/doc/search/auto-complete 实现了我自己的 Algolia PoC,我现在正在努力处理一个特定的用例:如何处理不返回任何命中的搜索?

这是我的代码:

我已经能够识别和检测何时/何地没有返回命中,但除了使用 console.log() 之外,我什么也做不了。我试图获取自定义 return_msg 但我无法调用该函数。 我还尝试根据建议进行一些调整:函数(建议),但如果没有返回命中,则永远不会调用此函数。 我也没有在https://github.com/algolia/autocomplete.js 上找到有关此“模板”部分的任何文档

$('#q').autocomplete({ hint: false }, [
    {
      source: function(q, cb) {
        index.search(q, 
          { hitsPerPage: 10 }, 
          function(error, content) {
                  if (error) {
                    cb([]);
                    return;
                  }

                  if (content.nbHits == 0)
                    { return_msg = '<h5> Sorry, no result </h5>';
                      // DO something here
                      console.log(return_msg);
                     // console.log return "Sorry, no result"
                     }

                  cb(content.hits, content);

                });
          },
      displayKey: 'game',
      templates: {
        suggestion: function(suggestion) {
          return_msg = '<h5> '+ suggestion.MY_ATTRIBUTE + '</h5>'
        return return_msg;
        }
      }
    }
  ]).on('autocomplete:selected', function(event, suggestion, dataset) {
     window.location = (suggestion.url);
  });

任何指针将不胜感激 =)

【问题讨论】:

    标签: javascript algolia


    【解决方案1】:

    使用数据集的templates 选项,您可以指定没有结果时要使用的模板:

    source: autocomplete.sources.hits(indexObj, { hitsPerPage: 2 }),
    templates: {
      suggestion: // ...
      header:  // ...
      footer:  // ...
      empty: function(options) {
        return '<div>My empty message</div>';
      }
    }
    

    完整文档here

    【讨论】:

    • 谢谢 - 完美运行.. 不知道为什么我在文档上错过了它们:/
    猜你喜欢
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    • 2018-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多