[SalesForce] Loading dynamic images as background, how can I check for image first

I am using dynamic images as the background image of a div in a visual force page I am working on. I apply the background to my div in CSS as follows:

background-image:url({!URLFOR($Action.Attachment.Download, AttachmentId)})

However there may not be an image available and when there is not then the VisualForce page crashes. I have figured out how to check it properly and use a default image when I am putting the image into an img tag as follows:

<apex:outputPanel rendered="{!!StaticImage}"> 
     <img src="{!URLFOR($Action.Attachment.Download, AttachmentId)}"/>
</apex:outputPanel>
<apex:outputPanel rendered="{!StaticImage}">
     <img src="{!DefaultImageName}" />
</apex:outputPanel>

My issue is that I don't know how or if it is even possible to apply this type of check to the background property in CSS instead of to an img tag?

Best Answer

Have you tried something like

background-image:url({!IF(ISBLANK(AttachmentId),
    StaticImage,
    URLFOR($Action.Attachment.Download, AttachmentId))
})

?

(I didn't try it plus it might require some extra apostrophes/quote signs to work!)

There's a chance URLFOR doesn't like to be conditionally used like that. But then you should still be able to write equivalent if-else in the Apex (if you have a controller extension there): How to specify an Action for an URLFOR in apex

Ugliest scenario to get it to work would be to hardcode the link:

IF(ISBLANK(AttachmentId), StaticImage, '/servlet/servlet.FileDownload?file=' + AttachmentId)
Related Topic