public
Last active

Simple EE conditionals turning advanced -- an example

  • Download Gist
gistfile1.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
// This will execute the exp:tag if first segment is empty
 
{if segment_1 != ''}
{exp:class:method}
{if var == "foo"}
Lorem
{if:else}
Ipsum
{/if}
{/exp:class:method}
{/if}
 
// This will NOT execute the exp:tag if first segment is empty
 
{preload_replace:ifelse="{if:else}"}
 
{if segment_1 != ''}
{exp:class:method}
{if var == "foo"}
Lorem
{ifelse}
Ipsum
{/if}
{/exp:class:method}
{/if}

When the ExpressionEngine template parser checks simple conditionals, it will also look for the string "if:else" inside it. If it finds it, the conditional is skipped, effectively leaving it to be parsed as an advanced conditional. However, it does not check if the if:else statement belongs to the same conditional it's actually checking at that moment. In the example above, the if:else is part of another (advanced) conditional, not part of the simple segment conditional.

Using a preload replace variable to replace {ifelse} with {if:else} will allow the simple conditional to be processed as such, while restoring the advanced conditional to the proper syntax before it is processed.

Read more about preload replace variables.

Optimisation, {exp:class:method attribute=""} would execute twice, even though only one is needed once...

Maybe something else too... but that's prob the most important thing...

Low, that is a funny trick, tricking the conditionals parser :-)
I use switchee a lot nowadays. It's a bit more difficult, but much more strong and supports regular expressions as well.
The above solution using switchee:

{exp:switchee variable="{segment_1}" parse="inward"}
    {case value="''"}
        {switchee variable="foo" parse="inward"}
            {case value="bar"}
                {exp:class:method attribute="lorem"}
            {/case}
            {case default="yes"}
                {exp:class:method attribute="ipsum"}
            {/case}
        {/switchee}
    {/case}
    {case default="yes"}
        {exp:class:method attribute="dolar"}
    {/case}
{/exp:switchee}

I've updated the gist to better demonstrate the principle I was trying to explain. No more 2 exp:tags, but a straight-forward advanced conditional inside an exp:tag for simple display purposes. The effect is the same.

Lodewijk, after reading your blog and checking the template parse method (The tag is, as mentioned, instantly replaced, leaving no other tag with the same name in the template to be replaced by a second declaration). But also, because the tag is instantly replaced, this opens the door for variable-variables :-)

{preload_replace:foo="{bar}"}
{preload_replace:bar="interesting"}

{foo} // returns: interesting

Indeed. But be aware that the order in which you place the variables here is important.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.