You can be a bit more terse and kinda get the best of both worlds nowadays with arrow syntax and Javascript String Interpolation. You get to avoid calling in an external library and still get nice code readability:
suggestion: d => `<p><strong>${data.value}</strong> - ${data.year}</p>`
Note that Javascript String Interpolation uses backticks instead of single quotes to start end end the string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
If you're using more elaborate JSON data rather than a simple array of strings, you should be aware of 3 things Typeahead is going to do to you that are not documented:
First, before getting to Typeahead, you are going to have to configure Bloodhound to tokenize the right part of your JSON. Assuming data like:
[ { id: 1, name: "Ford" }, { id: 2 ...
You'll need Bloodhound configured like:
{
identify: d => d.id,
datumTokenizer: d => Bloodhound.tokenizers.whitespace(d.name)
}
Once you apply your template:
display: 'name',
templates: {
suggestion: d => {
var s = d.name.replace(d._query, '<strong>$&</strong>');
return `<div>${s}</div>`;
}
}
You will be passed a mixin object. The JSON data in our example uses id/name pairs. The object passed to the suggestion function has that pair plus an inserted value _query
which contains a string, what the user has typed in the searchbox so far. So in the above, `d = { _query: 'f', name: 'Ford', id: 1 }
You become responsible for applying your own highlighting. In the above, I'm performing this with a simple replace - take the query and call String.replace on it with $&
wrapped in strong to leverage JS's builtin match insertion.
The template you return is going to get modified significantly. The tt- classes are going to get applied throughout, which by default is going to cause the above, simple template with a div and strong tag that has no classes applied...
...will actually render in the DOM like this:
<div class="tt-suggestion tt-selectable tt-cursor">
<strong class=tt-highlight>F</strong>ord
</div>
<div class="tt-suggestion tt-selectable">
<strong class=tt-hightlight>F</strong>ord F150
</div>
...
So your simple div and strong above are going to get a lot of tt- classes inserted. If you overrode those classes in your Typeahead config then obviously those classes will be applied instead. The tt-cursor
class tells you which one is currently keyboard-selected (with the up/down keys for example).
Edit: Markdown couldn't handle a transition from a numbered list to a code block, so I had to break it up with an awkward ellipsis break.