Switch / Case / Default
A switch
statement checks the source and compares it against several declared patterns. It then executes the first case
pattern that resolves to true
. or a default
one if nothing resolves to true (and default
is provided).
A switch
statement is equivalent to chaining multiple if
statements one after another.
Syntax
Basic syntax of switch
tag is as follows:
{[ switch [statement] ]}
{[ case 1 ]}
Executes when statement equals 1
{[/]}
You can chain as many cases one after another:
{[ switch [statement] ]}
{[ case 1 ]}
Executes when statement equals 1
{[ case 2 ]}
Executes when statement equals 2
{[ case 3 ]}
Executes when statement equals 3
{[/]}
Additionally, compared to strongly typed languages, you can check against multiple data types at the same time:
{[ switch [statement] ]}
{[ case 1 ]}
Executes when statement equals 1
{[ case true ]}
Executes when statement equals 2
{[ case "Some text" ]}
Executes when statement equals 3
{[/]}
Default fallback
Additionally, you can use default
case to fallback to it when all other cases fail. Default case is optional:
{[ switch [statement] ]}
{[ case 1 ]}
Executes when statement equals 1
{[ case 2 ]}
Executes when statement equals 2
{[ default ]}
Executes when statement equals to anything other than 1 or 2
{[/]}
Last updated
Was this helpful?