Home arrow Perl Programming arrow Page 8 - Getting Started with the Perl Template Toolkit

Dynamic Variables - Perl

This chapter compares the Template Toolkit to other templating systems such as HTML::Mason and HTML::Template, describes how to install it, then shows you what templates look like and how to process them. (From the book, Perl Template Toolkit, O'Reilly Media, ISBN: 0596004761, by Darren Chamberlain, Dave Cross and Andy Wardley.)

  1. Getting Started with the Perl Template Toolkit
  2. The Templating Ecosystem
  3. Installing the Template Toolkit
  4. Documentation and Support
  5. Using the Template Toolkit
  6. The Template Module
  7. The Template Toolkit Language
  8. Dynamic Variables
  9. Template Processing Directives
  10. Integrating and Extending the Template Toolkit
By: O'Reilly Media
Rating: starstarstarstarstar / 23
July 28, 2004

print this article



The examples that we’ve seen so far have used variables to store static values. When you set a variable to contain a scalar value or a reference to a list or hash array, it remains set to that value until the next time you explicitly modify it. Whenever the variable is used, the Template Toolkit simply looks up the current value for the variable and inserts it in the right place.

The Template Toolkit also allows subroutines and objects to be used to create dynamic variables. Each time such a variable is used, the Template Toolkit will call the subroutine or object method bound to it to return an appropriate value. Whereas static variables contain precomputed values, these dynamic variables return values that are recomputed each time they are used.

Example 1-11 shows a Perl program that defines two template variables, one bound to a subroutine, the other to an object.

use Acme::Planet;       # not a real module (yet)

my $vars = { 
    help => sub {
        my $entry = shift;
        return "$entry: mostly harmless";
    planet => Acme::Planet->new( name => 'Earth' ),

Example 1-11. Dynamic data in template variables

In this example, the help variable is a reference to a subroutine that expects a single argument, $entry. The planet variable references a hypothetical Acme::Planet object. This isn’t a real module (at the time of this writing), but we’re assuming that the new constructor method creates an Acme::Planet object against which we can invoke the name( ) method to return the value provided, Earth.

The following extract shows how these variables can be used in a template:

The guide has this to say about [% planet.name %].
[% help(planet.name) %]

This would generate the following output:

The guide has this to say about Earth.
  Earth: mostly harmless

Notice that when we call the name method on planet we use the dot operator in exactly the same way as we would if planet were a hash with a key called name. The Template Toolkit doesn’t care which of these we have, it just looks at the variable and works out what is the right thing to do. This illustrates how you are not tied down to any particular implementation for your underlying data structures, and can freely change from hashes to objects and back again without affecting the templates that use them.

Dynamic variables must be defined in Perl. There is no easy or clean way to define dynamic variables from within a template, other than by enabling the EVAL_PERL configuration option and using embedded Perl. The preferred solution is to write a simple Perl script that defines the relevant subroutines, objects, and other data items and then processes the appropriate template or templates. Another approach is to write a Template Toolkit plugin that encapsulates the Perl code and can be loaded into any template on demand. We look at plugins in detail in Chapter 6.

Virtual Methods

The Template Toolkit provides virtual methods for manipulating and accessing information about template variables. For example, the length virtual method can be applied to any scalar variable to return its string length in characters. The virtual method is applied using the dot operator:

[% name = 'Slartibartfast' %]
[%name%]'s name is [% name.length %] characters long.

This generates the output:

Slartibartfast's name is 14 characters long.

Virtual methods are provided for the three main variables types: scalars, lists, and hashes. The following example shows the join list virtual method being used to return the elements in a list joined into a single string. It adds a single space character between each item in the list by default, but you can provide a different delimiter by passing it as an argument in parentheses.

[% friends = [ 'Andy', 'Darren', 'Dave'] %]
Your friends are [% friends.join(', ') %].

This will display:

Your friends are Andy, Darren, Dave.

Some virtual methods alter the contents of the variable that they act on. For example, the pop method removes the last item from a list and returns it:

[% last = friends.pop %]
Your friends are [%friends.join(', ')%] and [%last%].

This will display:

Your friends are Andy, Darren and Dave.

We saw an example earlier of how virtual methods were combined in a dotted variable:

You know the following terms:
[% FOREACH term IN terms.keys.sort -%]
  [% term %]: [% terms.$term %]
[% END -%]

The part that we’re particularly interested in is this:


The terms variable contains a reference to a hash. The keys hash virtual method returns a reference to a list of the keys in the hash. The keys aren’t returned in any particular order, but now that we have a list, we can go on to call the sort list virtual method to return a second list containing the items sorted in alphabetical order.

We can then go one step further and call the join virtual method on that list, to join the items into a single string:

[% terms.keys.sort.join(', ') %]

This generates the following output:

frood, hoopy, sass

Virtual methods are covered in detail in Chapter 3.

Template Directives

The examples we have looked at so far have concentrated on the use of variables. The Template Toolkit also provides more advanced language constructs called direc tives. These begin with an uppercase keyword such as PROCESS, IF,or FOREACH and tell the template processing engine to do something.

Variable Directives

Given that directives start with an uppercase keyword, you might be forgiven for thinking that the examples we have seen so far don’t count as directives:

[% name = 'Arthur Dent' %]
[% planet = { name = 'Earth' } %]
Welcome [% name %] of [% planet.name %].

However, the syntax that we have been using until now to set and get variables is actually just a convenient shortcut for the full version, which uses the SET and GET keywords like so:

[% SET name = 'Arthur Dent' %]
[% SET planet = { name = 'Earth' } %]
Welcome [% GET name %] of [% GET planet.name %].

For obvious reasons, the shorter versions are used most of the time. 

Buy the book!If you've enjoyed what you've seen here, or to get more information, click on the "Buy the book!" graphic. Pick up a copy today!

Visit the O'Reilly Network http://www.oreillynet.com for more online content.

>>> More Perl Programming Articles          >>> More By O'Reilly Media

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Perl Turns 25
- Lists and Arguments in Perl
- Variables and Arguments in Perl
- Understanding Scope and Packages in Perl
- Arguments and Return Values in Perl
- Invoking Perl Subroutines and Functions
- Subroutines and Functions in Perl
- Perl Basics: Writing and Debugging Programs
- Structure and Statements in Perl
- First Steps in Perl
- Completing Regular Expression Basics
- Modifiers, Boundaries, and Regular Expressio...
- Quantifiers and Other Regular Expression Bas...
- Parsing and Regular Expression Basics
- Hash Functions

Developer Shed Affiliates


Dev Shed Tutorial Topics: