Conditional statement in jQuery template

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

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

+7
source share
1 answer

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

Computes the specified field (property) in the current data element, or the specified JavaScript function or expression.

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

So you can 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> 

JavaScript and JSON data are as follows:

 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 to the "orange" class for films with years greater than or equal to 1990, and the "yellow" class for films with years less than 1990.

A working example is here: http://jsfiddle.net/andrewwhitaker/dY43s/

+16
source

All Articles