Lesson 2.1: Variables and output
Pages are made of templates: HTML with expressions in curly braces. This lesson starts the template language with what every template does first: print a value, declare variables and escape what users typed. Learners build a small playground that renders a template on the command line, so they can try every expression of this module without touching a site's design.
At a glance
| Course | Developers |
| Module | Module 2: The template language |
| Duration | 50 minutes (15 presenting, 35 exercise) |
| Level | Beginner |
| Audience | Developers and template builders |
| Prerequisites | Lesson 1.4: extension/mysite_hello exists |
Learning objectives
After this lesson, learners can:
- render a template file from the command line with
eZTemplate::factory()andezexec.php; - print a variable and an attribute of it with
{$node.name}; - declare, change and free variables with
{def},{set}and{undef}; - build lists with
array()and named lists withhash(); - escape every value a user typed with
|wash.
Trainer's notes
How to present it
Source: Templates and design, part 6.
- What a template is (3 minutes). A
.tplfile is HTML with{ ... }expressions;{* ... *}is a comment. The kernel's templates live indesign/standard/templates/; opennode/view/full.tplon the projector. - The playground (3 minutes). Show the two files of the exercise.
eZTemplate::factory()gives the template engine,setVariable()hands it a value,fetch()renders a file and returns the text. - Variables and attributes (4 minutes).
{$node.name}reads the attributenameof the node. The same dot reads a key of a hash ({$person.name}) or an index ({$list.0});{$person['role']}works too. def,set,undef(3 minutes).{def}declares once per template; a second{def}of the same name gives a warning.{set}changes a declared variable.{undef}frees it at the end, a habit that avoids surprises in included templates.wash(2 minutes).{$value|wash}turns<into<. Use it on anything that comes from users: names, titles, search words. Rich text attributes are shown withattribute_view_guiinstead (lesson 2.6).
Common questions
Why def and not just set? def creates the variable in the current template; set changes one that
exists. A second def of the same name in one template writes the warning "Variable '...' is already defined",
which catches copy-and-paste mistakes.
Do I need undef? Variables live until the end of the template. Freeing them is good practice in templates
that are included many times, so nothing leaks between calls.
What about the old let and section? Older templates use {let} and {section}. They still work; new
templates use def and foreach.
Pitfalls
- Whitespace. A tag at the end of a line eats the line break after it; the playground output looks squeezed. That is normal.
- No
washon a title. A title with&or<breaks the page or opens a cross-site scripting hole. Make|washa reflex. - Missing attribute.
{$node.nonexistent}prints nothing, often without any message. When a value is unexpectedly empty, list the attributes the variable has with{$node|attribute( 'show' )}(lesson 2.4).
Hands-on exercise
On the development installation, from its root folder.
Create
extension/mysite_hello/scripts/play.php:// Template playground: php bin/php/ezexec.php extension/mysite_hello/scripts/play.php $tpl = eZTemplate::factory(); $tpl->setVariable( 'node', eZContentObjectTreeNode::fetch( 2 ) ); eZCLI::instance()->output( $tpl->fetch( 'extension/mysite_hello/scripts/play.tpl' ) );Create
extension/mysite_hello/scripts/play.tpl:{* My first template *} {def $title = $node.name $count = 3} <h1>$title|wash</h1> set $count = $count|inc <p>Count: $count</p> undef $title $countCheck both:
php -l extension/mysite_hello/scripts/play.phpandphp bin/php/eztemplatecheck.php extension/mysite_hello/scripts/play.tpl.Run the playground:
php bin/php/ezexec.php extension/mysite_hello/scripts/play.php.Add an array and a hash at the end of
play.tpland print parts of them:{def $colors = array( 'red', 'green', 'blue' ) $person = hash( 'name', 'Ada', 'role', 'editor' )} $colors.1 $person.name $person['role'] undef $colors $personRun it again.
Print a value with HTML in it, once without and once with
wash:{'<b>bold</b>'}and{'<b>bold</b>'|wash}. Run it and compare.Print three attributes of the node:
{$node.node_id},{$node.class_identifier},{$node.children_count}.Add
{def $count = 1}twice at the end of the file, and run the playground with the warnings shown:php bin/php/ezexec.php --debug=warning extension/mysite_hello/scripts/play.php. Read the warning, then remove the two lines.Commit both files in the extension's repository.
Expected result
- Step 4 prints
<h1>with the name of node 2 andCount: 4. - Step 6 adds
green Ada editor. - Step 7: the first prints
<b>bold</b>, the washed one<b>bold</b>. - Step 8 prints the ID 2, the class identifier (for example
folder) and a number. - Step 9: the debug section at the end names
play.tpl, line and column, with "Variable 'count' is already defined." - The trainer checks each learner's playground output on the screen.
Quiz
- How do you write a comment in a template?
- Which function changes the value of a variable that is already declared?
A.
defB.setC.undefD.let - What does
{$person.name}read when$personis a hash? - What does
|washdo with<? - True or false: a rich text attribute should be printed with
{$attribute.content|wash}.
Answers
{* ... *}.- B.
set;defdeclares,undeffrees. - The value under the key
name; the dot reads attributes of objects and keys of hashes alike. - It turns it into
<, so the browser shows the character instead of reading a tag. - False. Use
attribute_view_gui, which renders the rich text with its datatype template (lesson 2.6).
Further reading
- Templates and design: how templates are found, overrides, debugging.
- String template operators: the string operators of Exponential 6.
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.