Railo tip: using conditional assignments!

I saw this type of code popping up in some Railo source code, but for some reason did not use it before.

In javascript, I was already using it a long time: var a = (b>100) ? 100 : b, but in Railo? Not yet.

Well, that has changed now! It is much simpler then using IIF(), and has great power:

<cfset testValue = 107 />
<cfset nothigherThen100 = testValue gt 100 ? 100 : testValue />

And you can also use it inline:

<cfset testValue = 107 />
<cfoutput>#testValue# is #(testValue gt 100 ? 'greater then' : 'smaller or equal to')# hundred</cfoutput>

Off course, you can nest these statements:

<cfoutput>#testValue# is #(testValue gt 100 ? 'greater then' : (testValue eq 100 ? 'exactly' : 'smaller then'))# hundred</cfoutput>

If you are new to this concept, the syntax is really simple, once you get the hang of it: (also see Wikipedia)

[statement, evaluated to true or false] ? [value if statement is true] : [value if statement is false]

Pretty nifty eeh? [edit] And it works in Adobe Coldfusion 9 too. [/edit]

del.icio.us Digg StumbleUpon Facebook Technorati Fav reddit Google Bookmarks
| Viewed 3929 times
  1. Big Mad Kev

    #1 by Big Mad Kev - December 7, 2010 at 1:04 PM

  2. Paul Klinkenberg

    #2 by Paul Klinkenberg - December 7, 2010 at 1:29 PM

    Hi Kev, That's good to know! I googled to find out if "conditional assignments" were available in ACF, but didn't find it. I guess I should've googled for "Ternary Operator" then...
    Anyway, I'm still happy to have blogged about it, because this option just rocks! :-)
  3. Todd Rafferty

    #3 by Todd Rafferty - December 7, 2010 at 2:20 PM

    Except Railo has had ternary operators long before CF9 had them. :) Just sayin' :P
  4. Paul Klinkenberg

    #4 by Paul Klinkenberg - December 7, 2010 at 2:34 PM

    Todd, thanks for your comment! You just justified this blog post for still being a "Railo tip"! I was just about to change the title, but now I won't ;-)
  5. Todd Rafferty

    #5 by Todd Rafferty - December 7, 2010 at 2:38 PM

    Yeah, the 'What's new in Railo 3.1' which was released on March 31st 2009 shares 'Ternary Operator' ( http://blog.getrailo.com/post.cfm/what-s-new-in-railo-3-1 ). It's a good tip. I need to make sure it's on the Railo wiki somewhere too.
  6. kristof polleunis

    #6 by kristof polleunis - February 6, 2011 at 1:28 AM

    This is awesome and reduces the code required while still keeping it readable
(will not be published)
Leave this field empty