Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional operator in jQuery template

Does the new jQuery template plugin support conditional(ternary) operator? For printing a simple value depending on a condition, is {{if}}/{{else}} the only option?

I am interested in something similar to <?=($reviewed ? 'ham' : 'spam')?>

like image 405
Joyce Babu Avatar asked Dec 31 '10 12:12

Joyce Babu


1 Answers

Yes, you can put arbitrary functions and expressions inside the ${} template tag:

Evaluates the specified field (property) on the current data item, or the specified JavaScript function or expression.

${reviewed ? 'ham' : 'spam'}

So, you could write a template like this:

<script id="movieTemplate" type="text/x-jquery-tmpl">
    <!-- Ternary operator to assign a class -->
    <li class="${Year >= 1990 ? 'orange' : 'yellow'}">
        Title: ${Name}.
        {{each Languages}}
            ${$index + 1}: <em>${$value}. </em>
        {{/each}}
    </li>
</script>

Given JavaScript and JSON data like this:

var movies = [
{
    Name: "Meet Joe Black",
    Languages: ["French"],
    Year: 1990
}, 
{
    Name: "The Mighty",
    Languages: [],
    Year: 1985
}, 
{
    Name: "City Hunter",
    Languages: ["Mandarin", "Cantonese"],
    Year: 1994
}];

$("#movieTemplate").tmpl(movies).appendTo("#movieList");

This applies a class of 'orange' to movies with years greater than or equal to 1990 and a class of 'yellow' to movies with years less than 1990.

Working example here: http://jsfiddle.net/andrewwhitaker/dY43s/

like image 74
Andrew Whitaker Avatar answered Oct 06 '22 17:10

Andrew Whitaker