jQuery API

jQuery Plugin

{{if}} Template Tag

{{if fieldNameOrExpression}} content {{/if}}

Description: Used for conditional insertion of content. Renders the content between the opening and closing template tags only if the specified data item field, JavaScript function or expression does not evaluate to false (or to zero, null, type "undefined", or the empty string ).

  • version added: 1.4.3{{if fieldNameOrExpression}} content {{/if}}

    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 {{if}} tag can be used within jQuery templates in addition to text and HTML markup, in order 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}}, {{html}}, {{else}}, {{tmpl}} and {{wrap}}. User-defined template tags can also be specified, by extending the jQuery.tmpl.tag map.

Using the {{if}} Template Tag

The following example shows how to use {{if}} to insert conditional content, depending on whether the Languages field of the data item is defined (and is not null).

Template:
<li>
    Title: ${Name}.
    {{if Languages}}
        (Alternative languages: ${Languages}).
    {{/if}}
</li>
Data:
var movies = [
    { Name: "Meet Joe Black", Languages: "French" },
    { Name: "The Mighty" },
    { Name: "City Hunter", Languages: "Mandarin and Cantonese" }
];

Evaluating Expressions and Functions, Using Template Variables

{{if expression}} can be used in a similar way to ${expression}, to render conditionally based on the value returned by an expression or a function call, as in the following example:

Template:
<li>
    Title: ${Name}.
    {{if Languages.length}}
        (Alternative languages: ${$item.getLanguages(" - ")}).
    {{/if}}
</li>
Data:
var movies = [
    { Name: "Meet Joe Black", Languages: ["French"] },
    { Name: "The Mighty", Languages: [] },
    { Name: "City Hunter", Languages: ["Mandarin", "Cantonese"] }
];

See ${} for more detailed documentation and examples of using template tags in association with expression evaluation, function calls, template variables, etc.

Example:

Using {{if}} to render content conditionally, based on the value of an expression.

<!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>
        Title: ${Name}.
        {{if Languages.length}}
            (Alternative languages: ${$item.getLanguages(" - ")}).
        {{/if}}
    </li>
</tmpl>

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

<script>
var movies = [
    { Name: "Meet Joe Black", Languages: ["French"] },
    { Name: "The Mighty", Languages: [] },
    { 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 {{if}} 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 {{if}} Template Tag? Report it to the jQuery core team.

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

  • Tommy Leirvik

    What happends if the values from the json dont exists? ect. ${Expected.value} how to check if “undefined” ?

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

      If Expected does not have a value field, ${Expected.value} will render as the empty string. This default behavior is to support 'jagged arrays' where the field may be defined on some data items and not on others. If you want to test for defined, one easy way is to use {{if}} or {{else}}. See the example which does this in {{else}}.

      • Leirvik Tommy

        The solution was to check the first part and dont the value like: {{if Expected}} ${Expected.value} (This is for datastructures thats not the same each time)

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

          OK – so it is the Expected field on the data item that may be undefined, not the value field on the Expected object. In that case, yes, that's the solution.

          OTOH if it is the field itself that you are evaluating (of type string or number, say), you don't need to test first: ${thisMayOrMayNotBeDefined} is fine…

  • http://www.640pixels.com Carlo

    How to render the following data for example?

    I find the examples given are too simplistic and doesn't lend itself to real life examples, such as data returned as a data object from a .net method as below :

    {“d”:{“__type”:”_d+VehicleData”,”vehicles”:[{"VehicleId":"a244cf6a-f9cb-4426-99f4-39f4dfab738e","ManufacturerName":"Nissan","ModelName":"NP300 Hardbody","ModelDescription":null,"ModelYear":2005,"Price":100000,"VehiclePictureId":null,"VehiclePictureUrl":"imagedata/a244cf6a-f9cb-4426-99f4-39f4dfab738e/fc9d3a6e-dd61-4b80-b726-25502fad02d8.jpg","VehicleUrl":"/a244cf6a-f9cb-4426-99f4-39f4dfab738e/nissan-np300-hardbody.aspx"},{"VehicleId":"c041c578-2a57-4348-98ec-058c154c4dd2","ManufacturerName":"BMW","ModelName":"5 Series","ModelDescription":null,"ModelYear":2009,"Price":200000,"VehiclePictureId":null,"VehiclePictureUrl":"imagedata/c041c578-2a57-4348-98ec-058c154c4dd2/030bdeb8-c10e-4135-91d1-893d3708b876.jpg","VehicleUrl":"/c041c578-2a57-4348-98ec-058c154c4dd2/bmw-5-series.aspx"}],”totalRecords”:6}}

    How would I reference the vehicle object and iterate over that?

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

      {{each d.vehicles}}…{{/each}}.

      See also this tutorial for a bit more detail on how expressions are used in tags. And also the template tag topics for ${} and {{each}}…

  • http://programmerforhire.com.au JohnM

    The expression you put after the “if” can be any javascript expression eg:

    var redflag = “redflag”

    … class=”box{{if itemflag == redflag}} red{{/if}}”…

    Which certainly beats having to work out how to write and attach a method. Doesn't actually demonstrate this in the examples so thought I'd save you having to find out for yourself.

    • Alexey.S

      Maybe i made something wrong but i can't get
      {{if itemflag == redflag}} red{{/if}}
      working. In console i get error: “Uncaught ReferenceError: itemflag is not defined”.

      Only this worked for me:
      {{if $item.data.itemflag == redflag }} red {{/if}}

      • http://www.facebook.com/mhuggins Matt Huggins

        I had the same issue. I needed to prepend the variable with “$item.data.” when used in a conditional tag.

  • Maurettol86

    Hi, i can't find the reason why this not works..

    if ($(“.hidden”).length) {
    $(“#hidden warning”).html(“This post has hidden content”);
    };

    hope someone can help me!
    Thanks!