jQuery API

jQuery Plugin

jQuery.tmplItem()

jQuery.tmplItem( element ) Returns: tmplItem

Description: Return the tmplItem data structure for the rendered template that the specified element is part of.

  • version added: 1.4.3jQuery.tmplItem( element )

    elementAn HTML element (or jQuery object that wraps an element)

This documentation topic concerns the jQuery Templates plugin (jquery-tmpl), which can be downloaded from: http://github.com/jquery/jquery-tmpl.

Note: For information about how to render templates, see .tmpl() and jQuery.tmpl().

$.tmplItem( element ) provides access to the rendered template item which the element is part of.

See also tmplItem().

Typically the element parameter passed to tmplItem()is the this element within an event handler. The return value of tmplItem() is a tmplItem data structure whose fields provide access to:

  • The HTML elements that the template item is made up of (nodes field).
  • The associated data item (data field).
  • The parent template item, if the template is nested (parent field).
  • The template that was used to render the template item (tmpl field).
  • User defined parameters or methods, such as any values that were set on the options map, passed to tmpl() when the template was rendered.

The following example shows how to use $.tmplItem() to get information about the rendered template:

function myClickHandler() {
    var tmplItem = $.tmplItem( this );
    alert( "Description: " + tmplItem.data.description );
}

Building Interactive Ajax Applications

.tmplItem() and jQuery.tmplItem() make it easy to use templates in scenarios beyond simple string concatenation and read-only rendering. They let you create fully-fledged interactive client-side Ajax applications in which the code needs to perform actions like the following:

  • Accessing the associated data item.
  • Modifying the data item.
  • Accessing HTML elements that make up the rendered template item.
  • Updating (re-rendering) the template item, with modified data, modified user-defined parameters, or using a different template

Example: Dynamically switching templates for a template item.:

// Get the compiled detail template
var detailTemplate = $( "#detailTemplate" ).template();

// Add an onclick handler for template items currently 
// using the summary template
$(".movieSummary").live( "click", function () {
    // Get the data structure for the template item 
    // which this clicked element belongs to
    var tmplItem = $.tmplItem(this);

    // Set the template on this item to the detail template
    tmplItem.tmpl = detailTemplate;

    // re-render
    tmplItem.update();
})

Examples:

Example: Access the data, and set selection on the item.

<!DOCTYPE html>
<html>
<head>
  <style>
#movieList { cursor:pointer; color:blue; margin:8px; background-color:#f8f8f8; }
#movieList li:hover { color:red; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
  
<tmpl id="movieTemplate" type="text/x-jquery-tmpl"> 
    <li><b class="movieName">${Name}</b></li>
</tmpl>

Click for details:
<ul id="movieList"></ul>

<script>
var movies = [
    { Name: "The Red Violin", ReleaseYear: "1998" },
    { Name: "Eyes Wide Shut", ReleaseYear: "1999" },
    { Name: "The Inheritance", ReleaseYear: "1976" }
];
var selectedItem =  null;

/* Render the template with the movies data */
$( "#movieTemplate" ).tmpl( movies )
    .appendTo( "#movieList" );

/* Add an onclick handler for the movie template items */
$( ".movieName" ).live( "click", function() {

    if ( selectedItem ) {
        $( selectedItem.nodes ).css( "backgroundColor", "#f8f8f8" );
    }

    /* Get the data structure for the template item 
       which this clicked element belongs to */
    selectedItem = $.tmplItem( this );

    $( selectedItem.nodes ).css( "backgroundColor", "yellow" );

    alert( "'" + selectedItem.data.Name + "' was released in " 
        + selectedItem.data.ReleaseYear + "." ); 
});
</script>

</body>
</html>

Demo:

Example: Master detail view.

<!DOCTYPE html>
<html>
<head>
  <style>
table { cursor:pointer; border-collapse:collapse; float: left; clear: both; } table tr { border:1px solid blue; color:blue; height:25px; } table tr:hover { color:red; }
table, #personDetail > div { border:2px solid blue; width:220px; margin:8px 0 4px 0; background-color:#f8f8f8; } table td, #personDetail div div { padding:3px; margin:3px; }
.selected { background-color:yellow; } #personDetail input { float:right; width:125px; } #personDetail { float:left; margin-left:10px; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
  
<tmpl id="listItemTemplate" type="text/x-jquery-tmpl"> 
    <tr><td>
        ${firstName} ${lastName} 
    </td></tr>
</tmpl>

<tmpl id="detailTemplate" type="text/x-jquery-tmpl"> 
    <div>
        <div>First Name: <em>${firstName}</em></div>
        <div>Last Name: <em>${lastName}</em></div>
    </div>
</tmpl>

<div style="float:left;">Click for details:<div>
<table><tbody id="peopleList"></tbody></table>

<div id="personDetail"></div>

<script>
var people = [
    { firstName: "Peter", lastName: "Jones" },
    { firstName: "Eva", lastName: "Smolinski" }
];

var selectedItem = null;

function renderTemplate( container, template, data ) {
    $( container ).empty();
    $( template ).tmpl( data ).appendTo( container );
}

/* Render the list */
renderTemplate( "#peopleList", "#listItemTemplate", people );

$("#peopleList")
    .delegate( "tr", "click", function () {

        if ( selectedItem ) {
            $( selectedItem.nodes ).removeClass( "selected");
        }

        /* Set selection on the clicked item */
        selectedItem = $.tmplItem(this);
        $( selectedItem.nodes ).addClass( "selected");

        /* Render the detail view for this data item */
        renderTemplate( "#personDetail", "#detailTemplate", selectedItem.data );
    });
</script>

</body>
</html>

Demo:

Example: Dynamic switching of templates.

<!DOCTYPE html>
<html>
<head>
  <style>
table { cursor:pointer; border-collapse:collapse; border:2px solid blue; width:300px; margin:8px; }
table tr { border:1px solid blue; color:blue; background-color:#f8f8f8; } table td { padding:3px; } table tr:hover { color:red; }
.movieDetail { background-color:yellow; } .movieDetail.row1 { border-bottom:none; } .movieDetail.row2 { border-top:none; }
</style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
  
<tmpl id="summaryTemplate" type="text/x-jquery-tmpl">
    <tr class='movieSummary'><td colspan='2'>${Name}</td></tr>
</tmpl>

<tmpl id="detailTemplate" type="text/x-jquery-tmpl">
    <tr class='movieDetail row1'><td colspan='2'>${Name}</td></tr><tr class='movieDetail row2'><td>${ReleaseYear}</td><td>Director: ${Director}</td></tr>
</tmpl>

Click for details:
<table><tbody id="movieList"></tbody></table>

<script>
var movies = [
    { Name: "The Red Violin", ReleaseYear: "1998", Director: "François Girard" },
    { Name: "Eyes Wide Shut", ReleaseYear: "1999", Director: "Stanley Kubrick" },
    { Name: "The Inheritance", ReleaseYear: "1976", Director: "Mauro Bolognini" }
];
var selectedItem = null;

/* Render the summaryTemplate with the "movies" data */
$( "#summaryTemplate" ).tmpl( movies ).appendTo( "#movieList" );

/* Add onclick handlers for movie template items
   using the summary or details template */
$("#movieList")
.delegate( ".movieSummary", "click", function () {
    if (selectedItem) {
        // Set the template on the previously selected item
        // back to the summary template
        selectedItem.tmpl = $( "#summaryTemplate" ).template();
        selectedItem.update();
    }
    /* Get the data structure for the template item 
       which this clicked element belongs to, and make
       it the selected item */
    selectedItem = $.tmplItem(this);

    /* Set the template on this item to the detail template */
    selectedItem.tmpl = $( "#detailTemplate" ).template();
    selectedItem.update();
})
.delegate( ".movieDetail", "click", function () {
    /* Set the template on this item to the summary template */
    selectedItem.tmpl = $( "#summaryTemplate" ).template();
    selectedItem.update();
    selectedItem = null;
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with jQuery.tmplItem() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.tmplItem()? Report it to the jQuery core team.

Found a problem with this documentation? Report it on the GitHub issue tracker

  • ca

    “Typically the element parameter passed to tmplItem()is the this element within an event handler.”

    would be nice to see what the non-typical values for element could be.

    • http://www.borismoore.com Boris Moore

      Well say you want to get a template item from somewhere in the DOM and you already have a reference to an element within that item.
      For example the .tmplitem topic has an example to access the last item:

      var lastTmplItem = $( “li:last” ).tmplItem();

      If you already have a reference to the lastLi element, you could instead do

      var lastTmplItem = $.tmplItem( lastLi );

  • ca

    “Typically the element parameter passed to tmplItem()is the this element within an event handler.”

    would be nice to see what the non-typical values for element could be.

  • Luke Maurer

    What exactly are the names and values of the properties of the template item data structure? The bulleted list is not sufficient.

    • http://www.borismoore.com Boris Moore

      I have added the names of the corresponding fields, in the list above.

      • Luke Maurer

        Thanks!

  • Luke Maurer

    What exactly are the names and values of the properties of the template item data structure? The bulleted list is not sufficient.

  • http://blog.semanticsworks.com/ Fred Yang

    In the example,
    // Get the compiled detail template
    var detailTemplate = $( “#detailTemplate” ).template();

    // Add an onclick handler for template items currently
    // using the summary template
    $(“.movieSummary”).live( “click”, function () {
    // Get the data structure for the template item
    // which this clicked element belongs to
    var tmplItem = $.tmplItem(this);

    // Set the template on this item to the detail template
    tmplItem.tmpl = detailTemplate;

    // re-render
    tmplItem.update();
    })

    I think the tmplItem.update() should return the newly created item, instead of undefined, so that we can continue to work on the newly created item.

    • http://www.borismoore.com Boris Moore

      tmplItem.update() does not create a new template item, it re-renders the current one. You can continue working with the same template item as in:

      // re-render
      tmplItem.update();
      $(tmplItem.nodes).css(“color”, “green”);

      It may however create some new child template items, if you are switching to a template that includes nested templates.