Showcase and discover digital art at yex

Follow Design Stacks

Subscribe to our free newsletter to get all our latest tutorials and articles delivered directly to your inbox!

ColdFusion Tutorial – CFIF and CFELSE

Page 5 — CFIF and CFELSE


For that extra money you put out, you’ll be happy to know that ColdFusion does much more than output the contents of a database. It packs plenty of secret little gimmicks under the hood, including tag sets that vastly extend the capabilities of HTML.

The program’s documentation includes a complete reference to all tag sets plus instructions on how to develop your own custom tags. Allaire’s support pages offer scads of links to custom tags that other CF users have built for their applications; some are free, some aren’t. Note that if you’re running an older version of CF, some tags may not be supported.

Let’s check out the ever-useful <CFIF> and <CFELSE> tags.

In our table Contents we’re going to add a new field called Picture. It will contain a URL that points to a location on our site where we’ve stored a picture of each item in my pocket. If we just wanted to output a picture of each item along with the text describing it, we’d use a CFOUTPUT section like this:

<CFOUTPUT QUERY= "pocket">
Item: #Item# <BR>
<IMG SRC="#Picture#"> <BR>
</CFOUTPUT>

It’s no problem, because ColdFusion variables don’t mind being used as the source for <IMG>, <SRC>, or <A HREF> tags. But just to screw things up, let’s say that we have pictures for some of our items but not all of them. In our Contents table the items without pictures have an empty Picture field. If we used a standard CFOUTPUT section like the one above, we’d end up with several broken images.

So let’s use ColdFusion’s <CFIF> and <CFELSE> tags to set up a simple if-then statement that will check to see whether the Picture field contains text or not.

<CFOUTPUT QUERY= "pocket">
Item: #Item# <BR>

<CFIF #Picture# EQ"">
    <IMG SRC="my_generic_picture.jpg"> <BR>
<CFELSE>
    <IMG SRC="#Picture#"> <BR>
</CFIF>

</CFOUTPUT>

What we’ve done here is set up an easy test in which ColdFusion will examine our Picture field and do one thing if it is empty (NULL) and another if text appears there. In the above code, I used a generic picture that will appear for items that don’t have their own illustrations. It could be an under construction symbol, a picture of your mom in a bikini, whatever. If I didn’t want anything at all to appear there, I could have just left the line after the <CFIF> tag blank.

The test you perform on the CFIF line doesn’t have to be a simple NULL or NOT NULL check. You can also use computations, Boolean operators, and all that other stuff I don’t have the space to cover here. But you get the basic idea, right?

Comments