Entry

New Conditionals Parser in 2.9

by: Seth Barber on: 6/16/2014

In 2.9 we rewrote the conditional parser. It is more performant, more consistent, and has new operators.

Performance

{if segment_3 == 'books'}
    {exp:channel:entries channel="book_reviews" limit="5"}
        {title}
    {/exp:channel:entries}
{if:elseif segment_3 == 'games'}
    {exp:channel:entries channel="game_reviews" limit="5"}
        {title}
    {/exp:channel:entries}
{if:else}
    {exp:channel:entries channel="misc_reviews" limit="5"}
        {title}
    {/exp:channel:entries}
{/if}

Starting with 2.9 conditionals evaluate when ready. When a conditional statement’s variables are known the statement will be evaluated as either TRUE or FALSE. In the above example, when segment_3 is “games” we will remove the other two channel entries tags from the template. Instead of processing 3 channel entries tags and then deciding which one to show, we now determine which tag to process.

Consistency

The distinction between “simple” and “advanced” conditionals is gone. Write your conditionals anyway you want. Put the variable first ({if my_snippet == "awesome"}) or put it last ({if "awesome" == my_snippet}). Use as many if:elseif statements as you desire. Use boolean operators. They are now all evaluated when ready.

New Operators

We have added mathematical operators to our conditionals. In addition to the modulus operator (%) you can now add (+), subtract (-), multiply (*), divide (/), and compute exponents (^) on your numbers. We’ve also added a string concatenation operator (.):

{if segment_1."/".segment_2 == "site/index"}

We didn’t stop there. We’ve also added three special comparison operators, inspired by CSS attribute selectors: begins with (^=), ends with ($=), and contains (*=). Using a snippet of “Conditionals in ExpressionEngine 2.9 Rock!” named my_snippet these all evaluate to true:

{if my_snippet ^= "Conditionals"}
{if my_snippet $= "Rock!"}
{if my_snippet *= "ExpressionEngine 2.9"}

We also added a regular expression operator (~) so now you can do this:

{if segment_3 ~ "/^P\d+/"}
    I'm paginated!
{/if}

And for good measure we added a boolean not operator (!) so this works:

{if ! (segment_3 ~ "/^P\d+/")}
    No pagination here.
{/if}

Or if you prefer:

{if ! (the_droids *= looking_for)}

And if you want to ponder a philosophical point:

{if 2B || ! 2B}

These are some of the major new features of the new conditional parser in ExpressionEngine 2.9. We can’t wait to see what you do with it.

.(JavaScript must be enabled to view this email address) or share your feedback on this entry with @ellislab on Twitter.

ExpressionEngine News

#eecms, #events, #releases