The Velocity if element is used in conjunction with elseif and else to express multiple conditional tests.
Syntax:
#if( condition )
.. some output ..
#elseif( condition )
.. some output ..
#else
.. some output ..
#end
The code below will emulate the W3Schools choose page for XSLT. We will add a pink background color to the "Artist" column IF the price of the CD is higher than 10, and a grey background-color IF the price of the CD is higher than 9 and lower or equal to 10. ELSE the background-color will be white. Also take note of the use of $_EscapeTool.dollar to render a $ since that character is reserved in Velocity. Notice how it is contained somewhat in braces like ${_EscapeTool.dollar}$pricetext as this will separate the Velocity operation and variable and prevent errors since $_EscapeTool.dollar$pricetext would be problematic.
<table style="border: 3px solid #450084">
<tr style="background:#ccc999">
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
</tr>
#set($cds = $_XPathTool.selectNodes($contentRoot, '//catalog/cd'))
#foreach($cd in $cds) ##LOOP
#set ($artist = $cd.getChild('artist').value)
#set ($title = $cd.getChild('title').value)
#set ($pricetext = $cd.getChild('price').value)
#set ($price = $_MathTool.toDouble($pricetext) )
#if( $price > 10 )
<tr>
<td bgcolor="#fffccc">$title</td>
<td>$artist - ${_EscapeTool.dollar}$pricetext</td>
</tr>
#elseif( $price < 10 && $price > 9 )
<tr>
<td bgcolor="#cccccc">$title</td>
<td>$artist - ${_EscapeTool.dollar}$pricetext</td>
</tr>
#else
<tr>
<td>$title</td>
<td>$artist - ${_EscapeTool.dollar}$pricetext</td>
</tr>
#end ##IF
#end ##LOOP
</table>
My CD Collection
Title | Artist |
---|---|
Empire Burlesque | Bob Dylan - $10.90 |
Hide your heart | Bonnie Tyler - $9.90 |
Greatest Hits | Dolly Parton - $9.90 |
Still got the blues | Gary Moore - $10.20 |
Eros | Eros Ramazzotti - $9.90 |
One night only | Bee Gees - $10.90 |
Sylvias Mother | Dr.Hook - $8.10 |
Maggie May | Rod Stewart - $8.50 |
Romanza | Andrea Bocelli - $10.80 |
When a man loves a woman | Percy Sledge - $8.70 |
Black angel | Savage Rose - $10.90 |
1999 Grammy Nominees | Many - $10.20 |
For the good times | Kenny Rogers - $8.70 |
Big Willie style | Will Smith - $9.90 |
Tupelo Honey | Van Morrison - $8.20 |
Soulsville | Jorn Hoel - $7.90 |
The very best of | Cat Stevens - $8.90 |
Stop | Sam Brown - $8.90 |
Bridge of Spies | T`Pau - $7.90 |
Private Dancer | Tina Turner - $8.90 |
Midt om natten | Kim Larsen - $7.80 |
Pavarotti Gala Concert | Luciano Pavarotti - $9.90 |
The dock of the bay | Otis Redding - $7.90 |
Picture book | Simply Red - $7.20 |
Red | The Communards - $7.80 |
Unchain my heart | Joe Cocker - $8.20 |