BT

Your opinion matters! Please fill in the InfoQ Survey!

Introducing Templates for jQuery

| by Jonathan Allen Follow 186 Followers on Oct 07, 2010. Estimated reading time: 1 minute |

In the first of three new libraries created by Microsoft and accepted by jQuery as official plugins, the jQuery Templates API allows for the dynamic creation of HTML Elements from data objects. Like server-side templating languages such as ASP or VB’s XML Literals, one merely has to leave holes with data-binding expressions that indicate what should be displayed.

Basic data binding is done using the syntax ${fieldName}. For example:

  

<script id="bookTemplate" type="text/x-jquery-tmpl">
    <li><b>${Name}</b> (${Year})</li>
</script>

To use a template, simply define the target location and execute the template using the “tmpl” method.

  

<ul id="bookList"></ul>
$( "#bookTemplate" ).tmpl( books ).appendTo( "#bookList" );

Using this syntax, the template is compiled as a JavaScript function. Compiled templates can also be created form strings using jQuery.template function. Templates created in this fashion can be named, which stores them in the $.templates list, or simply returned as an object.

For single-use templates, the overhead of compiling them is often not worth the cost. In these situations you can pass the template definition as a string directly to the template execution function, jQuery.tmpl.

The jQuery Template API requires jQuery 1.4.2. It is licensed under both the MIT and GPL Version 2 licenses.

Rate this Article

Adoption Stage
Style

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Nothing new by Luca Guidi

What's the difference with Mustache?

Same notation with Tapestry by halil karakose

The same notation(${}) is also used in Tapestry templates. This API may not be compatible with Tapestry.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

2 Discuss

Login to InfoQ to interact with what matters most to you.


Recover your password...

Follow

Follow your favorite topics and editors

Quick overview of most important highlights in the industry and on the site.

Like

More signal, less noise

Build your own feed by choosing topics you want to read about and editors you want to hear from.

Notifications

Stay up-to-date

Set up your notifications and don't miss out on content that matters to you

BT