D
D
Developers
Search…
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:
1
{[ switch [statement] ]}
2
{[ case 1 ]}
3
Executes when statement equals 1
4
{[/]}
Copied!
You can chain as many cases one after another:
1
{[ switch [statement] ]}
2
{[ case 1 ]}
3
Executes when statement equals 1
4
{[ case 2 ]}
5
Executes when statement equals 2
6
{[ case 3 ]}
7
Executes when statement equals 3
8
{[/]}
Copied!
Additionally, compared to strongly typed languages, you can check against multiple data types at the same time:
1
{[ switch [statement] ]}
2
{[ case 1 ]}
3
Executes when statement equals 1
4
{[ case true ]}
5
Executes when statement equals 2
6
{[ case "Some text" ]}
7
Executes when statement equals 3
8
{[/]}
Copied!

Default fallback

Additionally, you can use default case to fallback to it when all other cases fail. Default case is optional:
1
{[ switch [statement] ]}
2
{[ case 1 ]}
3
Executes when statement equals 1
4
{[ case 2 ]}
5
Executes when statement equals 2
6
{[ default ]}
7
Executes when statement equals to anything other than 1 or 2
8
{[/]}
Copied!
Last modified 7mo ago
Copy link