switch

Summary

Allows conditional control of code execution.

Usage

{switch match=<variable>}

    {case match=<value>} 
    {case in=<array>}
    ...
    {/case}

    {case}
    ...
    {/case}

{/switch}

Description

This mechanism is similar to a series of IF statements used on the same expression. This construct is typically useful when the same variable needs to be compared to different values. It executes a piece of code depending on which value that matched a given criteria. A default case should always be provided.

Please note that it is also possible to match inside arrays. This can be done by making use of the "in" argument, it is demonstrated in the last (third) example.

Examples

Example 1

{def $fruits='oranges'}
 
{switch match=$fruits}
 
    {case match='apples'}
        Apples <br />
    {/case}
 
    {case match='oranges'}
        Oranges <br />
    {/case}
 
    {case}
        Unidentified fruit! <br />
    {/case}
 
{/switch}

The following output will be produced: "Oranges".

Example 2

{def $fruits='Hello world'}
 
{switch match=$fruits}
 
    {case match='apples'}
        Apples <br />
    {/case}
 
    {case match='oranges'}
        Oranges <br />
    {/case}
 
    {case}
        Unidentified fruit! <br />
    {/case}
 
{/switch}

The following output will be produced: "Unidentified fruit!" - which is the outcome of the default case (none of the other cases matched).

Example 3

{def $digit=1}
 
{switch match=$digit}
 
    {case in=array( 1, 2 )}
        This one matches.
    {/case}
 
    {case in=array( 2, 3 )}
        This one does not match.
    {/case}
 
    {case}
        Not this one either.
    {/case}
 
{/switch}

The following output will be produced: "This one matches.".

Powered by eZ Publish™ CMS Open Source Web Content Management. Copyright © 1999-2013 eZ Systems AS (except where otherwise noted). All rights reserved.