Simplifying jQuery tmpl interface
By Anatoly Mironov
In one of my previous posts I showed a simple example how to retrieve data from a web service and render it with jQuery tmpl. To render this I used an id for a template and the container:
<script id="contactTemplate" type="text/html">
<div>
Name: {{= Name }} <br>
Phone: {{= Phone }}
</div>
</script>
<div id="contactContainer"></div>
```To render we select the template and container with jQuery selectors:
function onSuccess(data) { $("#contactTemplate").tmpl(data.d.results).appendTo("#contactContainer"); }
(function ($, undefined) { if ($ === undefined) { throw “Dependency: jQuery is not defined. Please check javascript imports.”; } $.extend($.expr[’:’], { // :template(name) template: function (current, index, metadata, elements) { var arg = metadata[3], d = $(current).data(“template-for”); if (d === undefined) { return false; } return arg ? arg === d : true; }, // :container(name) container: function (current, index, metadata, elements) { var arg = metadata[3], d = $(current).data(“container-for”); if (d === undefined) { return false; } return arg ? arg === d : true; } }); } (jQuery));
Now we can forget the ids: