jQuery API

jQuery Plugin

jQuery.template()

Contents:

jQuery.template( name, template ) Returns: function

Description: Create a reusable named template (compiled from markup).

  • version added: 1.4.3jQuery.template( name, template )

    nameA string naming the compiled template.

    templateThe HTML markup and/or text to be used as template. Can be a string, or an HTML element (or jQuery object wrapping an element) whose content is to be used as 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 compiles the markup in the template parameter as a named template, which can be referenced using the string specified in the name parameter.

The return value is the compiled-template function.

See also template().

Note: The named template is added to the $.template map.

  • To determine if a string "someName" is the name of a named template, test whether $.template["someName"] is defined.
  • To remove a previously created named template, use
    delete $.template["someName"];

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

// Convert the markup string into a named template
$.template( "summaryTemplate", "<li>${Name}</li>" );

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:

// Convert the markup string into a compiled template
var myTemplate = $.template( null, "<li>${Name}</li>" ); 

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>
___________

// Convert the markup string into a named template,
// referenced by the {{tmpl}} tag
$.template( "summaryTemplate", "<tr><td>${Name}</td></tr>" );

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

Optimizing Template Rendering

When a template is rendered, using .tmpl() or jQuery.tmpl(), the markup is first converted into a compiled-template function. In the case of markup obtained from a string, the use of .template() as in the above examples ensures that the conversion from markup to a compiled-template function only happens once.

On the other hand, passing a markup string template directly to .tmpl() or to {{tmpl}} for rendering will not be optimal from a performance point of view, since the markup will be re-compiled every time:

var markup = "<li>${Name}</li>";

function renderList() {
  // Sub-optimal: the markup string will be
  // recompiled each time renderList is called
  $.tmpl( markup, movies ).appendTo( "#moviesList" );
}

Note: In the case of inline templates declared within a script block, caching occurs automatically, so the following example does correspond to best practice:

Example: Rendering an inline template directly without compiling as a named template.

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

function renderList() {
  // The template will be compiled only once,
  // so this is approach can be optimal.
  $( "#summaryTemplate" ).tmpl( movies ).appendTo( "#moviesList" );
}

Examples:

Example: Render template obtained from a markup string.

<!DOCTYPE html>
<html>
<head>
  <style>
table { border-collapse:collapse; margin:8px; background-color:#f8f8f8; }
table td { border:1px solid blue; padding:3px; }
</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>
  
<button id="showBtn">Show movies</button><br/>
<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 markup = "<tr><td colspan='2'>${Name}</td><td>Released: ${ReleaseYear}</td><td>Director: ${Director}</td></tr>"

/* Compile markup string as a named template */
$.template( "movieTemplate", markup );

/* Render the named template */
$( "#showBtn" ).click( function() {
  $( "#movieList" ).empty();
  $.tmpl( "movieTemplate", movies ).appendTo( "#movieList" );
});
</script>

</body>
</html>

Demo:

Example: Switch between templates obtained from markup strings.

<!DOCTYPE html>
<html>
<head>
  <style>
table { border-collapse:collapse; margin:8px; background-color:#f8f8f8; }
table td { border:1px solid blue; padding:3px; }
</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>
  
<button id="switchBtn">Show full details</button><br/>
<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" }
];

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

/* Compile markup as named templates */
$.template(
  "titleTemplate",
  "<tr><td>${Name}</td></tr>"
);
$.template(
  "detailTemplate",
  "<tr><td colspan='2'>${Name}</td><td>Released: ${ReleaseYear}</td><td>Director: ${Director}</td></tr>"
);

var details = false;

$( "#switchBtn" ).click( function() {
  details = !details;
  $(this).text( details ? "Show titles" : "Show full details" );
  /* Render using the other named template */
  renderTemplate( "#movieList", (details ? "detailTemplate" : "titleTemplate"), movies );
});

renderTemplate( "#movieList", "titleTemplate", movies );
</script>

</body>
</html>

Demo:

Example: Use a markup string as a nested template.

<!DOCTYPE html>
<html>
<head>
  <style>
table { border-collapse:collapse; border:2px solid blue; margin:8px; background-color:#f8f8f8; }
table tr { border:1px solid blue; } table td { padding:2px; }
.title { border-bottom:none; } .detail { 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="movieTemplate" type="text/x-jquery-tmpl"> 
  {{tmpl "titleTemplate"}}
  <tr class="detail"><td>Director: ${Director}</td></tr>
</tmpl>

<table><tbody id="movieList"></tbody></table>

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

/* Convert the markup string into a named template,
   referenced by the {{tmpl}} tag */
$.template( "titleTemplate", "<tr class='title'><td>${Name}</td></tr>" );

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

</body>
</html>

Demo:

jQuery.template( template ) Returns: function

Description: Returns a compiled-template function.

  • version added: 1.4.3jQuery.template( template )

    templateThe template markup to be compiled, or a string corresponding to a named 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().

If the template parameter is the name string for a named template created using $.template( name, template ), this method returns the compiled template for the named template (equivalent to $.template[name]).

Otherwise, if the template parameter is a string containing HTML markup, then this method will return a compiled template for the markup provided.

If the template parameter is a string containing pure text (no HTML tags), then the string is treated as a selector for an inline template, whose content will be used as markup. Similarly if template is an HTML element (or jQuery object wrapping an element), then the content will be used as markup for the returned compiled template.

Example: Switch the template item to a different template, using $.template( name ), :

// Create the compiled templates
$.template( "summaryTemplate", "<tr>...</tr>" );
$.template( "detailTemplate", "<tr>...</tr>" );

// Render the summaryTemplate with the "movies" data 
$.tmpl( "summaryTemplate", 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 = $.template( "detailTemplate" );
    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>
  
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;

/* Create the compiled templates */
$.template(
  "summaryTemplate",
  "<tr class='movieSummary'><td colspan='2'>${Name}</td></tr>"
);
$.template(
  "detailTemplate",
  "<tr class='movieDetail row1'><td colspan='2'>${Name}</td></tr><tr class='movieDetail row2'><td>${ReleaseYear}</td><td>Director: ${Director}</td></tr>"
);

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

$( "#movieList" )
.delegate( ".movieSummary", "click", function () {
  if (selectedItem) {
    /* Switch the template for this template item to
    the named template, then update the rendered item */
    selectedItem.tmpl = $.template( "summaryTemplate" );
    selectedItem.update();
  }
  selectedItem = $.tmplItem(this);
  /* Switch the template for this template item */
  selectedItem.tmpl = $.template( "detailTemplate" );
  selectedItem.update();
})
.delegate( ".movieDetail", "click", function () {
  /* Switch the template for this template item */
  selectedItem.tmpl = $.template( "summaryTemplate" );
  selectedItem.update();
  selectedItem = null;
});
</script>

</body>
</html>

Demo:

Support and Contributions

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

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

  • http://kathawa.myopenid.com/ Bara

    Is it possible to create a template from an external HTML file? I would really like to have my templates be re-usable throughout my application, so having all of the markup inline isn't as convenient.

    • BorisMoore

      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

      • chovy

        This did not appear to work for me. Can you provide a simple example loading a template file from a script tag?

        How do I get a handle on the template itself?

        • http://twitter.com/oscargodson Oscar Godson

          It took me a few tries too until I realized this is NOT included with jQuery even though it says it is. You need to include it:
          <script src=”http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js”></script>

          I wish they'd remove the “Version added 1.4.3″ to this page. Completely confusing.

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

            Well each topic states that it concerns the jQuery Templates plugin (jquery-tmpl), which can be downloaded from: http://github.com/jquery/jquery-tmpl.

            The jquery.tmpl script is available from that github repository, or as Oscar says, from the CDN at “http://ajax.microsoft.com/ajax…“. (Each demo includes a script reference to the script…)

            The jQuery version is more to do with the version the plugin depends on…

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

          The best way to provide a template via a static script is to provide the template as a string in the script, and to compile it as a named template (as explained above) either in your static script, or in inline script. For example:

          template1.js:
          var template1Markup = “<li>${foo}</li>”;
          // Compile the template
          $.template( “template1″, template1Markup );

          <script type=”text/javascript” src=”template1.js”></script>

          <script type=”text/javascript”>
          $.tmpl( “templatet1″, data ).appendTo(“#results”);
          </script>

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

      The best way to provide a template via a static script is to provide the template as a string in the script, and to compile it as a named template (as explained above) either in your static script, or in inline script. For example:

      template1.js:
      var template1Markup = “<li>${foo}</li>”;
      // Compile the template
      $.template( “template1″, template1Markup );

      <script type=”text/javascript” src=”template1.js”></script>

      <script type=”text/javascript”>
      $.tmpl( “templatet1″, data ).appendTo(“#results”);
      </script>

      • Dylan Rosario

        I have another way of doing this much easier. See next comment.

  • http://twitter.com/yoxview YoxView

    Any plans to add conditions to templates?
    For example, a boolean value (or truthy/falsy statement) in the data object might display or not some text or image.

    “<div>${!!imageUrl ? “<img src=”${this}”>” : ''}</div>”

    Thanks for the great work, I really love this feature!
    Yossi.

    • http://borismoore.com Boris Moore

      Yes, it is already there. Take a look at the template tag topics for {{if}} and {{else}}

      • http://twitter.com/yoxview YoxView

        Oh, I didn't notice. Looks great!
        I think it'd be a good idea to make a comment on the conditional tags on this page as well, make it easier for people who got directly here.

  • Warwick Bracken

    What about iterating through n-deep objects? Is there a simple notation for that?

    • http://borismoore.com Boris Moore

      Take a look at the template tag topics for {{each}}, {{tmpl}} and {{wrap}}. They all allow you to iterate over data, and to nest tags, so you can drill down into hierarchical data.

      • http://twitter.com/rapextras rapextras

        thank you – i just realized as I was going over to “git”-me a copy of this to test it out, when I recalled it was you… nice (scratch that) outstanding work.

        tho I don't use smarty templates in parsing html, there are a good many who do, and thus it would make avg html'rs go from zero-hero in just this ONE plugin of jquery… again, well done.

  • Mark

    How to I evaluate bool? This always evals to false, even when the JSON data is true (really true, not just a “true” string)

    {{if Active}}Active{{else}}Inactive{{/if}}

    • Mark

      Never mind, I just realized only this did not work {{if !Active}} the normal {{if Active}}Active{{else}}Inactive{{/if}} works fine

  • http://twitter.com/rapextras rapextras

    Uh, er… i'm really baffled… this is a plugin!? OMG! I'd think this would be a part of the core – pretty soon. This is really gonna make back-end html'ing rather non-existent… and push (ahem! those of us using MVC and other like patterns with ) 'view's separate from the code… to the forefront…

    whoever DID create/develop these should win a jQuery Emmy :)

  • Jordan

    In the documentation above, it claims that the existence of a template may be tested:

    “To determine if a string “someName” is the name of a named template, test whether $.templates["someName"] is defined.”

    However, $.templates is undefined no matter how many precompiled templates I load.

    • Nick Franceschina

      yes, I just noticed this… you have to use $.template["someName"]
      documentation is incorrect

  • ca

    what's the best way to keep multiple -separate- templates in a single scrip tag? is it not advisable to do this for any (performance) reason? seems that it would be better to have related templates in a single script tag, to avoid dozens of script tags on the page or many ajax calls?

    i haven't tried this, but would something like this be a good approach?

    var templateX = $(templateScriptTag).find(templateSelector);
    jQuery.template( “myTemplateX”, templateX );

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

      See my reply below on remote templates as scripts.

      Following that approach, you can define several named templates in the same script:

      $.template( “template1″, template1Markup );
      $.template( “template2″, template2Markup );

  • fasteater

    Is there a way to preserve events bound to items in a template? I'm working with a third party tool (Telerik) that renders clientside controls without delegate binding.

  • Zannino Francesco

    Can I use a json variables as data for the template ?

  • Zannino Francesco

    Oh , yes !!! very great plug in.
    All jquery plugins are great.

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

    Well each topic states that it concerns the jQuery Templates plugin (jquery-tmpl), which can be downloaded from: http://github.com/jquery/jquery-tmpl.

    The jquery.tmpl script is available from that github repository, or as Oscar says, from the CDN at “http://ajax.microsoft.com/ajax…“. (Each demo includes a script reference to the script…)

    The jQuery version is more to do with the version the plugin depends on…

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

    The best way to provide a template via a static script is to provide the template as a string in the script, and to compile it as a named template (as explained above) either in your static script, or in inline script. For example:

    template1.js:
    var template1Markup = “<li>${foo}</li>”;
    // Compile the template
    $.template( “template1″, template1Markup );

    <script type=”text/javascript” src=”template1.js”></script>

    <script type=”text/javascript”>
    $.tmpl( “templatet1″, data ).appendTo(“#results”);
    </script>

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

    See my reply below on remote templates as scripts.

    Following that approach, you can define several named templates in the same script:

    $.template( “template1″, template1Markup );
    $.template( “template2″, template2Markup );

  • http://twitter.com/dariobarila Dario Barilà

    Thank you Boris, this rock! Is like Dancing with Data! ;)

  • http://twitter.com/Gopithpa Gopi Thapa

    Thank u

  • Rafay

    I would better go with jTemplates… they are awesome in case of separation of Template html files in another directory… and calling them as setTemplateUrl('/Templates/MyTemplate.htm')

  • Kaisellgren

    “Note: The named template is added to the $.templates map.”

    This is wrong. They exist within jQuery.template map.

  • smith

    ..would be interesting to know exactly what involvement M$ have had in this project..

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

    For jQuery templates, basically one developer (me). You can see different contributions here http://github.com/jquery/jquery-tmpl/graphs/impact