Using variables in a CFIF statment

Posted by Dark Training on March 18, 2009 tags: | coldfusion

One of the great things about Coldfusion, PHP or any other web language is that you can set a variable, better yet a GLOBAL variable that can be referenced across many pages. This makes life easier since if you want to make a change to site or directory, you only have to change the code in one place.

So what happens when you want to use a variable in a CFIF statment? It doesn't work, or at least not as you think it would.

In this example lets assume that I want to use a variable from my cfapplication.cfm file inside my CFIF statements. I want to have image displayed at the top of the page that says "Administrators" for the guys in the Admin team and "Users" for the folks that are in the user team. First I need to set the variable in the cfapplication.cfm file that gets the cookie.userid I have set. If you don't know how to set a cookie in coldfusion check out this link Abode KB.

<cfset admins = #cookie.userid# is 'bob' or #cookie.userid# is 'Jane>
<br/>
<cfset users = #cookie.userid# is 'John' or #cookie.userid# is 'Joe>

Now all I have to do in the actual coldfusion file is call that global variable like this:

<cfif "#admins#">Admins>/cfif><br/>

<cfif "#users#">Users>/cfif><br/>

If the cookie login thing is throwing you off, here is a more simple example

<cfset animal = 'dog'><br/>

<cfset tree = 'pine'><br/>

<cfif "#animal#" is 'dog'>Woof>/cfif><br/>

<cfif "#tree#" is 'dog'>I'm not a dog>/cfif><br/>

<cfif "#tree#" is 'pine'>I'm a tree!>/cfif><br/>

That is how you can use a variable in a coldfusion cfif statement. Feel free to leave questions below