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')?>
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With