jQuery API

jQuery Plugin

.template()

.template( [name] ) Returns: function

Description: Compile the contents of the matched element as a reusable compiled template.

  • version added: 1.4.3.template( [name] )

    nameA string naming the compiled template.

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().

This method returns a compiled template, created from the content of the first matched element. If the name parameter is provided the compiled template is stored as a named template, and can be referenced using the specified string.

See also jQuery.template().

Example: Create a compiled template associated with the name "summaryTemplate" and then reference it by name for rendering:

<script id="titleTemplate" type="text/x-jquery-tmpl">
  <li>${Name}</li>
</script>
___________

// Compile the inline template as a named template
$( "#titleTemplate" ).template( "summaryTemplate" );

function renderList() {
  // Render the movies data using the named template: "summaryTemplate"
  $.tmpl( "summaryTemplate", movies ).appendTo( "#moviesList" );
}

Example: Use the return value rather than the name string to reference the compiled template:

<script id="titleTemplate" type="text/x-jquery-tmpl">
  <li>${Name}</li>
</script>
___________

// Compile the inline template as a named template
var myTemplate = $( "#titleTemplate" ).template();

function renderList() {
  // Render movies data using the compiled template: myTemplate
  $.tmpl( myTemplate, movies ).appendTo( "#moviesList" );
}

Example: Create a named template and reference it by name as a nested template:

<script id="movieTemplate" type="text/x-jquery-tmpl">
  {{tmpl "summaryTemplate"}}
  <tr><td>Director: ${Director}</td></tr>
</script>

<script id="titleTemplate" type="text/x-jquery-tmpl">
  <tr><td>${Name}</td></tr>
</script>
___________

// Compile the titleTemplate template as a named template
// referenced by the {{tmpl}} tag
$( "#titleTemplate" ).template( "summaryTemplate" );

// Render the movies data using the named template as a nested template
$( "#movieTemplate" ).tmpl( movies ).appendTo( "#movieList" );

Example: Switch the template item to a different template, using .template() to obtain compiled template:

<script id="summaryTemplate" type="text/x-jquery-tmpl">
  <tr>...</tr>
</script>

<script id="detailTemplate" type="text/x-jquery-tmpl">
  <tr>...</tr>
</script>
___________

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

$( "tr" ).click( function () {
  // Switch the template for this template item to
  // a different named template, then update the rendered item
  var tmplItem = $.tmplItem(this);
  tmplItem.tmpl = $( "#detailTemplate" ).template();
  tmplItem.update();
});

Example:

Dynamic switching of templates, using .template() to obtain compiled template.

<!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" );

$("#movieList")
.delegate( ".movieSummary", "click", function () {
  if (selectedItem) {
    /* Switch previously selected item back to the summaryTemplate */ 
    selectedItem.tmpl = $( "#summaryTemplate" ).template();

    /* Update rendering of previous selected item */ 
    selectedItem.update();
  }

  /* Make this the selected item  */
  selectedItem = $.tmplItem(this);

  /* Switch this template item to the detailTemplate */ 
  selectedItem.tmpl = $( "#detailTemplate" ).template();

  /* Refresh rendering */ 
  selectedItem.update();
})
.delegate( ".movieDetail", "click", function () {
  /* Unselect - switch to the summaryTemplate */ 
  selectedItem.tmpl = $( "#summaryTemplate" ).template();

  /* Refresh rendering */ 
  selectedItem.update();

  selectedItem = null;
});
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .template() 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 .template()? Report it to the jQuery core team.

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

  • Chris Marstll

    hi – is there a simple way to load a template from a file, as EJS allows you to do?

    • http://borismoore.com Boris Moore

      Yes, for remote templates, you can get a template markup as a string using any AJAX call you want, or you can simply use a static script block pointing to a js file which defines the string. Then you should use jQuery.template to compile the template from the string, and go from there, rendering it using jQuery.tmpl

  • Tamas Flamich

    It would be nice if you could use remote templates like this:

    <script id=”mytemplate” src=”./mytemplate.tmpl” type=”text/html”>

    var compiledTemplate = $(“#mytemplate”).template();

    Doesn't seem to work now.</script>

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

      Yes, but the browser will not load that, and provide access to its content. We'll look at other ways of making this scenario really easy, though…

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

        For now, see this reply and this reply for one possible approach.

  • http://twitter.com/molokostov Viktor Molokostov

    Hi, all!
    Nice thing! Does anybody know some converter from php-templates (raw php used) to jquery ones?

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

    Yes, see this reply and this reply.

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

    For now, see this reply and this reply for one possible approach.

  • lashtal

    Examples here use <script …=”" type=”text/x-jquery-tmpl”> as a container tag for content.
    However using a simple div instead of script tag will trigger a bug(?) in IE-all.
    see http://pastebin.com/ibv3pjty for details.
    </script>

    • http://encosia.com Encosia

      Template markup is often an invalid fragment of markup on its own. Including that within markup that the browser interprets as an HTML document can have unpredictable results.

      A common example is a template that contains a table row. If you include a <tr> within a <div>, many (most?) browsers will try to correct your invalid HTML by wrapping a <table> around it. Then, when you access the <div>'s contents at runtime, jQuery Templates will be given that modified markup as your template instead of what you'd expect.

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

    Yes, see this reply and this reply.