The if statement allows for conditional processing of code blocks. In case the given expression evaluates to false, an optional else block is processed instead.
<@ if @{ variable } > 5 @>
...
<@ else @>
...
<@ end @>
Expressions
Automad understands two types of expressions. You can either test whether a variable has a value, or compare two operands. Operands can be variables, strings or numbers.
<# Test if a variable has a value. #>
<@ if @{ variable } @>
...
<@ end @>
<# Compare a variable to the string 'Test'. #>
<@ if @{ variable } = 'Test' @>
...
<@ end @>
<# Test whether a variable is greater than 5. #>
<@ if @{ variable } > 5 @>
...
<@ end @>
A variable is considered empty in case it is not defined or its value is either 0, false or an empty string.
Comparison Operators
The following operators can be used to compare two operands:
- =
- Equality — true if both operands have the same value.
- !=
- Inequality — true if both operands are not equal.
- >
- Greater than — true if the left operand is greater than the right one.
- >=
- Greater or equal — true if the left operand is greater than or equal to the right one.
- <
- Smaller than — true if the left operand is smaller than the right one.
- <=
- Smaller or equal — true if the left operand is smaller than or equal to the right one.
Logical Operators
The following operators can be used to negate or combine expressions:
- !
- Negates a variable test — true if a variable is empty.
- not
- An alias for
!. - and
- Combines two expressions — true if both expressions evaluate to
true. - or
- Combines two expressions — true if at least one of them evaluates to
true.
Multiple expressions can also be chained to one combined expression:
<@ if not @{ variable1 } and @{ variable2 } = 'Test' or @{ variable3 } > 5 @>
...
<@ end @>
Examples
Testing whether a variable is not empty:
<@ if @{ variable } @>
...
<@ end @>
To invert the test above, use the ! or not operators:
<# Using "not" #>
<@ if not @{ variable } @>
...
<@ end @>
<# Or alternatively "!" #>
<@ if !@{ variable } @>
...
<@ end @>
Testing values with a default:
<@ if @{ variable | def (1) } >= 5 @>
...
<@ end @>
Combining expressions in order to test a range:
<@ if @{ variable } >= 5 and @{ variable } < 10 @>
...
<@ end @>
Filters can also be used in expressions. The following example is taken from the Standard Lite theme and only includes a table of contents in case the template name contains _toc:
<@ if @{ template | match ('/_toc/') } @>
<@ toc.php @>
<@ end @>