I'm using jQuery Templates from within the jQuery UI Autocomplete plugin so that I have better control over how my autocomplete results are rendered. What I'd like to do is highlight the input within the result. http://jqueryui.com/demos/autocomplete/combobox.html is a good example of what I'm trying to achieve, only I'd like to use jQuery Templates to do it.
Here's what I have so far (with some of the autocomplete code abstracted out):
<script>
// in this example, this.term == 'dog'
$('#tmplProject').tmpl({text: "All About Dogs"},
{term: this.term, highlight: function(text) {
return text.replace(new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(this.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>" );
}}) )
</script>
<script id="tmplProject" type="text/x-jquery-tmpl">
some other markup goes here. ${$item.highlight(name)}
</script>
The problem is, the <strong>
element is getting escaped, and All about <strong>Dog</strong>s
is showing up in the browser. but this kind of makes sense, because the template should be where the markup is, not the highlight method. So how do I separate the logic of the highlight method from the markup that gets produced?
Does the {{html}} tag work for you?
Like this: http://jsfiddle.net/rniemeyer/baY3k/