Velocity Coding Example - Item Multimedia Conditional
Introduction
This tutorial shows how to use velocity code and conditional statements within your catalog templates to display an item's multimedia. This velocity code example is intended to be used with the catalog templates.
Sample Code
#if($item.getMultimedia("Image") && $item.getMultimedia("Image").size() > 0) <a href="$item.getDefaultMultimedia('Image').getViewUrl()" title="$item.getDescription()"> <img src="$baseThumbnailUrl$item.getDefaultMultimedia('Image').getThumbnail(240)" alt="$item.getDescription()" width="240" height="240" /> </a> #else <img src="$baseUrl/assets/images/200x200_default.jpg" alt="Image coming soon"/> #end
Breaking Down The Code
Here we are checking the item to see if there are any multimedia files with the code "image". If this isn't done, we risk throwing an error caused by calling .size() on a null object. If the condition is true the following code is output:
Condition
#if($item.getMultimedia("Image") && $item.getMultimedia("Image").size() > 0)
This is what is created if the default image is found.
Statement One
<a href="$item.getDefaultMultimedia('Image').getViewUrl()" title="$item.getDescription()"> <img src="$baseThumbnailUrl$item.getDefaultMultimedia('Image').getThumbnail(240)" alt="$item.getDescription()" width="240" height="240" /> </a>
If there is no multimedia uploaded to the item with the code "Image" then the #else condition is true and the following code is output:
Statement two
<img src="$baseUrl/assets/images/200x200_default.jpg" alt="Image coming soon"/>
This line displays a default image as a place holder until an image can be uploaded for the item.