Kendo UI's template API lets you use JavaScript
in the template
. This is useful to customize the autocomplete template.
When the generated code runs, the scope of this
is the Window object. I want to set the scope to the autocomplete instance, for example, to use the _prev
value to customize the results.
On this demo code, to change the color
of the customer's name to red on the substring
equivalent to the search text, you can search for the autocomplete
instance within the template
code. On the given sample, just change the template
property to
template:
'<span class="k-state-default"><img src= \"../content/web/Customers/#:data.CustomerID#.jpg\" alt=\"#:data.CustomerID#\" /></span>' +
'<span class="k-state-default">'+
'# var searchText= $("\\#customers").data("kendoAutoComplete")._prev; #'+
'# data.coloredName= '+
'"<span style=\\"color:red;\\">" ' +
'+ data.ContactName.substring(0, searchText.length) +' +
'"</span>" + data.ContactName.substring(searchText.length); #'+
'<h3>#= data.coloredName #</h3>'+
'<p>#: data.CompanyName #</p>'+
'</span>',
However, if I can't use the $()
"search", I would want to do it by setting the scope of the function generated by the template. Is it possible?
It is possible:
var autocomplete = $("#customers").kendoAutoComplete({
// standard options, not the template
}).data("kendoAutoComplete");
var templateHtml = 'your template html using "this" here ...';
// compile the template from the html
var compiledTemplate = kendo.Template.compile(templateHtml);
// bind the template function to whatever you want, e.g. the autocomplete
var boundTemplate = compiledTemplate.bind(autocomplete);
// set the template on the widget
autocomplete.setOptions({
template: boundTemplate
});
(demo)
Note that any properties you may have on the context will get overridden by the data that is passed to the template, so you can't access those from the outer scope (see structure of the template function here).