Earlier, in the article How To: Load KendoUI Templates from External Files, we were talking about the way to combine project's templates into a single file using Text Templates. Now, we would like to suggest the next step.
KendoUI defines text templates that it knows to transform into functions, at runtime obviously. Thus a template like this:
<tr> <td data-bind=" text: name"></td> <td>#: kendo.toString(get("price"), "C") #</td> <td data-bind="text: unitsInStock"></td> <td><button class="k-button" data-bind="click: deleteProduct"> Delete</button></td> </tr>
is transformed into a function:
function(data) { var o,e=kendo.htmlEncode; with(data) { o='<tr><td data-bind="text: name"></td><td>'+ e( kendo.toString(get("price"), "C") )+ '</td><td data-bind="text: unitsInStock"></td>' + '<td><button class="k-button" ' + 'data-bind="click: deleteProduct">Delete</button></td></tr>'; } return o; }
The transformation is done through a sequence of of regex replaces.
Now, what's the fastest javascript template engine?
Right! That, which does not work at runtime.
What we thought is that we can generate those functions at compile time rather than defining templates.
We have updated templates.tt to generate template functions, and optionally to generate <script> tags that call those functions. This way, for an input footer.tmpl.html:
<script>
<!DOCTYPE html> <html> <head> <title>Test</title> <base href="/" /> <link href="styles/kendo.common.min.css" rel="stylesheet" /> <link href="styles/kendo.default.min.css" rel="stylesheet" /> </head> <body> <table data-template-id="view"> <tr> <td>Products count: #: total() #</td> <td>Total price: #: totalPrice() #</td> <td colspan="2">Units in stock: #: totalUnitsInStock() #</td> </tr> </table> </body> </html>
templates.js will look like this:
nesterovskyBros.templates= { ... "footer-view":function(data) { var o,e=kendo.htmlEncode; with(data) { ... } return o; }, ... }; document.write('<script id="footer-view-template" type="text/x-kendo-template">#=nesterovskyBros.templates["footer-view"](data)#</script>');
To get template function at runtime you simply refer to nesterovskyBros.templates["footer-view"].
nesterovskyBros.templates["footer-view"]
template.tt now allows you to specify:
scope
nesterovskyBros.templates
data-script
true
data-with-block
with(data) {...}
See a sample application that shows how nicely KendoUI UserControls work with those compiled templates.