jQuery API

jQuery Plugin

${} Template Tag

${fieldNameOrExpression}

Description: Used for insertion of data values in the rendered template. Evaluates the specified field (property) on the current data item, or the specified JavaScript function or expression.

  • version added: 1.4.3${fieldNameOrExpression}

    fieldNameOrExpressionThe name of a field on the current data item, or a JavaScript function or expression to be evaluated.

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

Template Tags

Template tags such as the ${} tag can be used within jQuery templates in addition to text and HTML markup to enable a number of scenarios such as composition of templates, iteration over hierarchical data, parameterization of template rendering, etc.

Other available tags include: {{each}}, {{if}}, {{else}}, {{html}}, {{tmpl}} and {{wrap}}.
Note: User-defined template tags can also be specified, by extending the jQuery.tmpl.tag map.

Using the ${} Template Tag

The following example shows how to use ${} to insert the values of the data item fields: Name and ReleaseYear.

<script id="movieTemplate" type="text/x-jquery-tmpl">
    <li><b>${Name}</b> was released in ${ReleaseYear}.</li>
</script>

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

    // Render the template with the movies data and insert
    // the rendered HTML under the "movieList" element
    $( "#movieTemplate" ).tmpl( movies )
        .appendTo( "#movieList" );
</script>

<ul id="movieList"></ul>

The ${field} syntax is a shortened form of the alternative syntax: {{= field}}. The following is equivalent to the template used in the example above:

<li><b>{{= Name}}</b> was released in {{= ReleaseYear}}.</li>

Evaluating Expressions and Functions

In the following example ${expression} is used to evaluate a simple expression:

Template:
<tr><td>${Languages.length}</td></tr>
Data:
var movies = [
    { Name: "Meet Joe Black", Languages: ["English", "French"] },
    { Name: "The Mighty", Languages: ["English"] },
    { Name: "City Hunter", Languages: ["Mandarin", "Cantonese"] }

For more complex expressions it is preferable to place the expression within a function, then use ${myFunction(a,b)} to call the function, as in:

Template:
<tr><td>${getLanguages(Languages, " - ")}</td></tr>
Code:
function getLanguages( data, separator ) {
    return data.join( separator );
}

The above example requires the function getLanguages to be available in global scope. An alternative approach which does not require a global variable is to add the function to the template item, by passing it in with the options parameter of .tmpl():

Template:
<tr><td>${$item.getLanguages(" - ")}</td></tr>
Code:
// Render the template with the movies data
$( "#movieTemplate" ).tmpl( movies, { 
    getLanguages: function( separator ) {
        return this.data.Languages.join( separator );
    }
}).appendTo( "#movieList" );

Note the use of the $item template variable, above (see the next section), which corresponds to the template item. In the call to $item.getLanguages(), the this pointer within the function is therefore the template item, and provides access to this.data etc.

The $item and $data Template Variables

The following variables are exposed to expression evaluation within templates:

  • $: The jQuery object.
  • $item: The current template item - which allows access to $item.data, $item.parent, etc. as well as any user-defined values or methods passed in with the options map.
  • $data: The current data item (equivalent to $item.data).
  • Note: A template tag with content such as {{each}}...{{/each}} may expose additional variables to template evaluation within the content. In the case of {{each}}, for example, the additional template variables $value and $index are provided within the content of the {{each}} tag.

HTML encoding

The values rendered by ${} are evaluated as strings, and are HTML encoded. Any embedded markup will therefore be encoded. To insert the unencoded markup in the rendered template, use instead the {{html}} template tag.

Examples:

Example: Using ${} to render values of data item fields.

<!DOCTYPE html>
<html>
<head>
  <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>${Name}</b> was released in ${ReleaseYear}.</li>
</tmpl>

<ul id="movieList"></ul>

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

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

</body>
</html>

Demo:

Example: Using ${} to evaluate an expression or call a function.

<!DOCTYPE html>
<html>
<head>
  <style>
table { border-collapse:collapse; width:400px; background-color:#f8f8f8; margin:10px; } table td { border:1px solid blue; padding:3px; } 
table th { font-weight:bold; border:2px solid blue; padding:1px; } table tbody { border:2px solid blue; }
</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"> 
    <tr>
        <td>${Name}</td>
        <td>${Languages.length}</td>
        <td>${$item.getLanguages(" - ")}</td>
    </tr>
</tmpl>

<table><tbody><tr><th>Title</th><th>Versions</th><th>Languages</th></tr></tbody>
<tbody id="movieList"></tbody></table>

<script>
var movies = [
    { Name: "Meet Joe Black", Languages: ["English", "French"] },
    { Name: "The Mighty", Languages: ["English"] },
    { Name: "City Hunter", Languages: ["Mandarin", "Cantonese"] }
];

/* Render the template with the movies data */
$( "#movieTemplate" ).tmpl( movies, { 
    getLanguages: function( separator ) {
        return this.data.Languages.join( separator );
    }
}).appendTo( "#movieList" );
</script>

</body>
</html>

Demo:

Support and Contributions

Need help with ${} Template Tag 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 Tag? Report it to the jQuery core team.

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

  • Jason

    Leave it up to Microsoft to use characters that conflict with another technology. The ${} is used in JSP's Expression Language. Great idea, poor execution.

    • http://twitter.com/vitor_canova Vitor Canova

      Jason

      You can use {{= field}} instead.

      • BorisMoore

        Yes, as Vitor says, you can use {{= field}} instead. Even then, there can be conflicts, for example with Django template tags. It is impossible to guarantee against future conflicts, whatever we choose, so we may consider providing an option to modify the delimiter character.

      • Jason DiMeo

        That is good to know. Thank you! I can't wait to try this out.

      • http://twitter.com/rmariuzzo Rubens Mariuzzo

        This is the same answer I would say to Jason.

      • http://ddotsenko.myopenid.com/ Daniel Dotsenko

        Got burned by this while trying $.tmpl (git master circa Oct 5).

        {{= field}} is acceptable. {{=field}} no worky.

        Rather strange.

        For anyone using programming editor {{=*}} is likely an easier thing to type than ${} because the programming editor would auto-insert the closing bracket, so all 3 chars “{“,”{“,”=” can be typed with one hand and are next to eachother. However, having to insert a space kills this “tremendously” :) efficient way of inserting template vars.

        Seriously, it's not a big deal, but not having to type space for {{=var}} would be nice.

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

          Daniel, see my comment here for more background on this.

    • http://twitter.com/barneycarroll Barney Carroll

      You say that, but try using John's original syntax in an ASP environment ;)

  • http://twitter.com/vitor_canova Vitor Canova

    What about # of interaction. I tried to paint each even row of table with some color but I sow that appear template is not build in order. I wrote a function like that:

    var n = 0;

    var Increment = function(){

    return ++n === 0 ? “even” : “odd”;

    }

    And tried to use like that:

    <tr class=”${Increment()}”><td>${SomeData}</td></tr>

    I saw results like that sometimes:

    “odd”

    “even”

    “odd”

    “odd”

    “even”

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

      Vitor, the problem here is that your Increment() function has side-effects, and is being called during template rendering. Functions called as part of template rendering should not have side-effects, and should be able to be called one or more times, without returning different results each time.

      Here is an example of alternating styles on even/odd rows, based on https://github.com/jquery/jquery-tmpl/blob/master/demos/samplesCore/parameters.html:

      function alternate() {
      return ($.inArray( this.data, people ) % 2) ? “personAlt” : “person”;
      }

      <tr class=”${alternate()}”><td>${firstName}</td></tr>

  • http://twitter.com/cvillu cvillu

    You can load the outline of a template using ajax and then generate the html?

    • http://twitter.com/vitor_canova Vitor Canova

      You can use a page like a template or something like that and load with ajax, but imagine that you are responsable for the cache of that ajax request. Don't request every time and configure the server to responses with the properly http code.

  • http://nfplee.myopenid.com/ Lee

    Is there a way to format a date returned from json using the globalization plugin. I tried doing:

    {{= $.format(new Date(parseInt(comment.DateCreated.substr(6))), 'd')}}

    Where ${comment.DateCreated} displays:

    /Date(1288709830000)/

  • Ole

    It would be very nice if it was possible to change the symbols used as delimiters, since the { }-delimeters conflicts with the template system we're currently using.

    Could be done by using the options paramter on .tmpl(data, [options]):
    $(“#myTemplate”).tmpl( data, { delimiter : { “delimeter1″ ,”optionaldelimiter2″ } } );

  • Grebe

    Where a template traverses an array automatically, it would be useful to have the equivalent of the $index that appears within a {{each}} … construct.

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

      See my reply here.

  • http://twitter.com/Enome Geert Pasteels

    In Jinja2 you can use {% raw %} to escape.

    http://jinja.pocoo.org/templat…

  • Tauren

    Looks like jquery-tmpl conflicts with Underscore.JS
    http://documentcloud.github.co…/

    This means you can't use any underscore functions, such as to get the size of a javascript object. For instance, with the following data:

    var objects = {a:1, b:2, c:3};

    This template won't work:

    There are ${_.size(objects)} objects.

    This is because in the context of a template, the value of _ has been set to the content of the template.

    I've worked around this by defining a new global for underscore:

    var underscore = _;

    Then in my template:

    There are ${underscore.size(objects)} objects.

    I'm going to suggest in the issue tracker that __ (double underscore) be used inside of jquery.tmpl.js instead of _ (single underscore) to avoid this collision.

  • Jason DiMeo

    My apologies.

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

    This has been requested a few times, and will be addressed in an upcoming version: http://github.com/nje/jquery-t…

  • http://twitter.com/Enome Geert Pasteels

    In Jinja2 you can use {% raw %} to escape.

    http://jinja.pocoo.org/templat…