Algolia搜索:访问结果on {

时间:2016-01-26 08:25:21

标签: javascript ruby-on-rails search algolia

我正在使用algolia search作为我的rails应用,我使用typehead.js坐下了自动完成方法。但是当我在URL中使用大写字母时,我无法正确重定向...这是我的代码:

    // replace YourIndexName by the name of the index you want to query.
var index = algolia.initIndex('Pin');

// Mustache templating by Hogan.js (http://mustache.github.io/)
var template = Hogan.compile('<div class="hit">' +
  '<a href="http://yhumans.com/{{{twitter}}}">'
 +
  '<div class="small-text">' +
    '{{{ _highlightResult.name.value }}} ' +
  '</div>' +
  '<div class="small-text">' +
    '@' +
    '{{{ _highlightResult.twitter.value }}} ' +
  '</div>' +
  '</a>' +
  '</div>');


// typeahead.js initialization
$('#user-search').typeahead(null, {
  source: index.ttAdapter({ hitsPerPage: 5 }),

  displayKey: 'twitter',
  templates: {
    suggestion: function(hit) {

      // select matching attributes only
      hit.matchingAttributes = [];
      for (var attribute in hit._highlightResult) {
        if (attribute === 'name' || attribute == 'twitter') {
          // already handled by the template
          continue;
        }
        // all others attributes that are matching should be added in the matchingAttributes array
        // so we can display them in the dropdown menu. Non-matching attributes are skipped.
        if (hit._highlightResult[attribute].matchLevel !== 'none') {
          hit.matchingAttributes.push({ attribute: attribute, value: hit._highlightResult[attribute].value });
        }
      }

      // render the hit using Hogan.js
      return template.render(hit);

    }
  }
});

问题在于我用这条线让用户点击结果来访问页面:

<a href="http://yhumans.com/{{{twitter}}}">'

事实上,我的一些用户在其Twitter用户名中使用了大写字母,因此我无法在搜索结果中正确地重定向到他们的个人资料。

让我解释一下:http://yhumans.com/myname是一个正确的网址。 http://yhumans.com/MyName是一个错误的网址  我尝试使用小写字母表示该变量:&#34; twitter&#34;。但我找不到合适的方法。

我知道这样做的一种方法是小写twitter变量。但问题是功能&#39; downcase!&#39;似乎不适用于js。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

首先,两条评论不会直接回答问题,但是相关:

  • 使用Hogan模板时,如果文本中不包含HTML,则应使用{{variable}};如果文本不应包含HTML,则应使用{{{variable}}}。这就是你应该使用{{twitter}}
  • 的原因
  • Algolia实际上将typeahead.js@0.10分成了autocomplete.js,你应该看一下。

话虽如此,你给出了一个解决方案,即使你是对的,.downcase!不存在,它实际上是.toLowercase()
在您的建议功能中,只需将twitter属性改为小写:

function (hit) {
  hit.twitter = hit.twitter.toLowerCase();
  // ...
}

处理自动完成重定向的方法的一个问题是用户将无法使用他/她的键盘来选择结果。同时使用autocomplete.jstypeahead.js的推荐方法是分别使用autocomplete:selectedtypeahead:selected事件:

$('#user-search').typeahead(/* ... */).on('typeahead:selected', function (ew, selection, dataset) {
  // Redirect to http://yhumans.com/my-twitter-name
  window.location.href = 'http://yhumans.com/' + selection.twitter;
});

要在用户悬停或使用箭头选择结果时向用户显示当前选择,您可以使用.aa-hintautocomplete.js)或.tt-hint设置不同的背景颜色(typeahead.js)。