问题
I've found this "hack" to use jTemplates with the jQuery UI Autocomplete:
http://www.shawnmclean.com/blog/2011/02/using-jqueryui-autocomplete-with-jtemplates/
but, is there a way to use the official jQuery template plugin with jQuery UI Autocomplete? I would just use the demo in the link, but prefer a cleaner method if possible.
(It's necessary to use templates because I'm using them elsewhere in the site and would like to use the consistent layout for the autocomplete items without having to maintain two versions.)
回答1:
OK, jQuery UI makes this extremely easy. From the demo on page http://jqueryui.com/demos/autocomplete/#custom-data, you can just alter the .data() call:
//this is the original code in the demo
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.label + "<br>" + item.desc + "</a>" )
.appendTo( ul );
};
and replace it with this .data() call:
.data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "#myTemplate" ).tmpl( item ).appendTo( ul );
};
// template
<script id="myTemplate" type="text/x-jquery-tmpl">
<li><a>${label}<br />${desc}</a></li>
</script>
and here's the working code in a fiddle: http://jsfiddle.net/swatkins/XXeDd/
回答2:
i have looked for something similar with handlebars.... so here it is:
html:
<li>
<div class="myTemplate" >
<li><a>{{label}} "----" {{value}}</a></li>
</div>
</li>
js:
define([
'jquery',
'underscore',
'backbone',
'marionette',
'handlebars',
'filter_input',
'text!modules/search/templates/search.html',
'text!modules/search/templates/autocompleate.html',
'jqueryui'
],
function($, _, Backbone, Marionette, Handlebars, filter_input, tmpl, tmplAutocompleate, jqueryui) {
this.ui.search.autocomplete({
source: availableTags,
delay: 500,
// minLength: 2,
autoFocus: true,
success: function (data) {
response(
$.map(data.campagins, function (item) {
return {
label: item.name,
status: item.status,
id: item.id
}
}))
}
}).data("autocomplete")._renderItem = function(ul, item) {
var template = Handlebars.compile(tmplAutocompleate);
var html = template(item);
return $(html).appendTo(ul);
};
}
回答3:
I used underscore template and had a lot of issues getting it to work with Autocomplete using the method above. The data('ui-autocomplete-item', item )
(formally "item.autocomplete") That was removed in the above example is still required. I was able to keep it in by using the following method.
.data("ui-autocomplete")._renderItem = function(ul, item) {
return $('<li>').data('ui-autocomplete-item', item ).append(_.template($('#tmp').html(), item)).appendTo(ul);
};
Hope this helps anyone.
来源:https://stackoverflow.com/questions/7288232/is-there-a-way-to-use-jquery-templates-official-plugin-with-jquery-ui-autocomp