How to customize Bootstrap typeahead layout/function for more than just text?

后端 未结 3 1976
囚心锁ツ
囚心锁ツ 2021-01-31 11:39

I\'m working on a search functionality for my website and I\'m using Bootstrap\'s typeahead to show the results. So far so good. But what I want is to extend the function so tha

3条回答
  •  爱一瞬间的悲伤
    2021-01-31 12:19

    Typeahead expects that everything passed into the process callback from the source callback will be a string. Unfortunately, this means that your highlighter callback is somewhat limited in the kind of HTML it can generate since you can only modify a string so much.

    You can, however, define your source method such that it returns the usual array of string objects each of which have an additional data property that contains all the data you'll need to generate HTML in the highlighter.

    $('.typeahead').typeahead
      source: (query, processCallback)->
        $.get '/users', q: query, (data)->
          processCallback data.map (user)->
            item = new String("#{user.first_name} #{user.last_name}")
            item.data = user
            item
    

    In this form, item will be passed around the internals of typeahead as a string, and when it finally reaches your custom highlighter, you can use the data property to build more complex html:

    $('.typeahead').typeahead
      highlighter: (item)->
        " #{item}"
    

提交回复
热议问题