Lesson 2.2: Conditions and logic
Templates decide: show the image if there is one, a different heading for the front page, a message when a list is empty. In this lesson learners write conditions, meet the comparison and logic operators, and learn the two ways of writing an operator: as a pipe after a value, or as a function.
At a glance
| Course | Developers |
| Module | Module 2: The template language |
| Duration | 45 minutes (15 presenting, 30 exercise) |
| Level | Beginner |
| Audience | Developers and template builders |
| Prerequisites | Lesson 2.1: the template playground |
Learning objectives
After this lesson, learners can:
- write
{if},{elseif}and{else}blocks; - compare values with
eq,ne,gt,lt,geandlein pipe and function form; - combine tests with
and(),or()andnot(); - choose a value inline with
cond()andfirst_set(), and test for a variable withis_set(); - branch on one value with
{switch}and{case}.
Trainer's notes
How to present it
Source: Templates and design, part 6
and the operator lists in lib/eztemplate/classes/eztemplateautoload.php.
- Two forms of one operator (3 minutes).
{$node.depth|gt( 2 )}and{gt( $node.depth, 2 )}are the same test. The pipe passes the value on its left as the first input. - Comparisons (3 minutes).
eq,ne,lt,gt,le,ge.eqtakes several values:{$a|eq( 'x', 'y' )}is true only when all are equal. - Logic (3 minutes).
and( ... ),or( ... ),not( ... ), and the constantstrue()andfalse(). - Truthiness (2 minutes). A non-empty string is true; an empty array is false.
{if $node.name}works,{if array()}goes to{else}. - Inline and fallback (2 minutes).
cond( $test, 'yes', 'no' )is the inline condition;first_set( $a, $b, 'default' )returns the first value that exists. switch(2 minutes).{switch match=$value}{case match=3}...{/case}{case}...{/case}{/switch}: thecasewithoutmatchis the default.
Common questions
How do I test whether an array holds a value? {if array( 'folder', 'article' )|contains( $node.class_identifier )}.
contains also works on strings: {'folder'|contains( 'old' )} is true.
Is there a !=? No symbols: use ne or not( eq( ... ) ).
What does is_set do for an attribute that does not exist? is_set( $node.missing ) is false. Use it when a
template may be included with or without a parameter.
Pitfalls
eqwith several values.{$x|eq( 'a', 'b' )}does not mean "a or b". Usecontainson an array for that.- Wrong closing tag. Every
{if}needs{/if}. A wrong closing tag is reported byeztemplatecheck.phpwith the template and line ("Unterminated tag"); a missing{/if}at the very end of a file may pass the check, so count opening and closing tags in long templates. - Strings and numbers.
$node.depth|eq( '1' )and|eq( 1 )compare as PHP does; prefer numbers for numbers.
Hands-on exercise
Use the playground from lesson 2.1. Replace the content of extension/mysite_hello/scripts/play.tpl at each step
or add below it, and run php bin/php/ezexec.php extension/mysite_hello/scripts/play.php after each step.
Write a condition on the depth of the node:
if $node.depth|eq( 1 )top levelelseif $node.depth|lt( 4 )near the topelsedeep/ifWrite the same test in function form:
{if eq( $node.depth, 1 )}top level{/if}.Combine two tests:
if and( $node.depth|eq( 1 ), $node.children_count|gt( 0 ) )top level with children/ifTest the class with an array:
if array( 'folder', 'article' )|contains( $node.class_identifier )a folder or an article/ifUse
cond()to printvisibleorhidden:{cond( $node.is_hidden, 'hidden', 'visible' )}.Use
first_set()for a variable that was never declared:{first_set( $subtitle, 'No subtitle' )}.Write a
switchon the number of children:{switch match=$node.children_count} {case match=0}no children{/case} {case}some children{/case} {/switch}Change the
{/if}of step 1 into{/foreach}and runphp bin/php/eztemplatecheck.php extension/mysite_hello/scripts/play.tpl. Read the message, then put{/if}back.Commit the template.
Expected result
- Each step prints one short phrase; when node 2 is a visible folder at the top of the tree, step 1 prints
top level, step 4a folder or an article, step 5visible, step 6No subtitle. - Step 8: the checker prints
parser errorwith the file, line and column,Unterminated tag "if" does not match tag "foreach", andTemplate file invalidinstead ofTemplate file valid. - The trainer checks by asking two learners to explain their output of step 3.
Quiz
- Write the test "depth greater than 2" in pipe form.
- What does
{cond( false(), 'a', 'b' )}print? A.aB.bC. nothing D.false - How do you test whether
$node.class_identifierisfolderorarticle? - What does
first_set( $x, 'fallback' )return when$xwas never declared? - True or false:
{if array()}goes to the{else}branch.
Answers
{$node.depth|gt( 2 )}.- B.
condreturns the value after the first true condition, here the last value. {array( 'folder', 'article' )|contains( $node.class_identifier )};eqwith two values would need all three to be equal.'fallback'.- True. An empty array is false.
Further reading
- Templates and design: the language in ten minutes and debugging.
- Role and policy template operators: conditions on what the current user may do.
Related pages
- Module 2: The template language
- Developers: course overview
- Trainers: start here
- Free documentation: this page is free to copy, translate and improve under the GNU FDL 1.3.
Become an Exponential Partner
Partners share their information, provide funding, contribute back and develop the products with us, and that is how Exponential grows. A partner website and dashboard are planned for mid-2027: please become a partner today to speed up our growth rate and land new features faster.