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

Template Processing Directives - 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.)

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Another use of template directives is for changing the way templates are processed. The PROCESS directive is one of the simplest. It loads another template file, processes the contents, and inserts the generated output in the calling template:

[% PROCESS header %]

The Template Toolkit provides the INCLUDE_PATH option, which allows you to specify one or more directories where your template files can be found. This allows you to specify your templates with simple names such header, rather than full file paths such as /home/dent/templates/lib/header, for example.

The reason that it is called INCLUDE_PATH and not PROCESS_PATH becomes obvious when we mention that there is also an INCLUDE directive. The INCLUDE directive and related INCLUDE_PATH option have been part of the Template Toolkit, and the Text:: Metatext module that preceded it, from the very beginning. The PROCESS directive, on the other hand, was added at a later date, and was able to reuse the INCLUDE_PATH option for the same purposes.

The difference between PROCESS and INCLUDE is revealed in Chapter 2. For now it suffices to know that INCLUDE is most often used when you want to pass variable values that should remain local to that one template:

[% INCLUDE header
      title = 'Vogon Poetry'
%]

The Template Toolkit is quite relaxed about how you lay out directives. You can add as little or as much whitespace as you like (including newlines) to help make your directive more readable. The only rule is that you must separate individual words and phrases in the directive (e.g., the INCLUDE keyword and the header template name that follows it) with at least one whitespace character. You donít need any spacing between the opening tag and the start of the directive, or between the end of the directive and the closing tag, but we recommend it to help make directives easier to read.

The following examples are all valid and equivalent ways of writing the same directive:

[%INCLUDE header title='Vogon Poetry'%]

[% INCLUDE header title='Vogon Poetry' %]

[% INCLUDE header
         title = 'Vogon Poetry'
%]

Loops

The FOREACH directive allows you to create loops, where a block of template content is processed, once for each item in a list. Hereís the general form:

[% FOREACH item IN list %]
   block of template content...
   ...can contain directives...
   ...and reference the [% item %] variable...
[% END %]

Weíve already seen a real example of this in action:

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

We know from looking at virtual methods earlier that the terms.keys.sort variable returns a list of the items frood, hoopy, and sass. So our loop block will be repeated three times, with the term variable set to each of those values in turn. We print the term followed by its definition, fetched from the terms hash array using the value of term as the key. The term variable must be prefixed with $ to indicate that the value of the variable should be used rather than the literal string term:

[% term %]: [% terms.$term %]

The output generated for the complete block is as follows:

You know the following terms:
  frood: really, amazingly together guy
  hoopy: really together guy
  sass: know, be aware of, meet, have sex with

Conditionals

Conditionals are another powerful language feature that allow your templates to make decisions about what to process and what not to process, based on the values of variables and more complex expressions.

We saw an example of the IF directive in Example 1-3, shown here in condensed form for brevity:

[% IF order.destruction %]
   As you will no doubt be aware...
[% ELSE %] 
   Our representatives will be...
[% END %]

If the order.destruction variable is true, the first block, between the IF and ELSE directives, is processed. Otherwise, the block between the ELSE and END is used.

The notion of truth is, in this sense, the same as it is for Perl. If the variable is defined and contains any kind of value except an empty string or the number zero, both Perl and the Template Toolkit will consider it to be true. If the variable is undefined, or contains a zero-length string or the number zero, it is false. This applies to all Template Toolkit directives that perform operations based on evaluating a variable or more complex expressions for truth.

Filters, Plugins, and Macros

Thereís plenty more in the Template Toolkit that we introduce in the chapters that follow. The following examples give a taste of what is to come.

Filters allow you to postprocess the output of a block of template markup. The html filter, for example, will convert any HTML-sensitive characters, such as <, >, and &, into their equivalent HTML entities, <, >, and &.

[% FILTER html %]
   Home > Dent > Friends > Slartibartfast
[% END %]

This generates the following output, which, when displayed as HTML on a web browser, will show the original > characters as intended:

Home > Dent > Friends > Slartibartfast

See Chapter 5 for further details.

Plugins allow you to load and use Perl modules in templates without having to write a Perl wrapper program to do it for you. The following examples show how the CGI plugin (which delegates to Lincoln Steinís CGI.pm module) can be used for CGI programming:

[% USE CGI %]
[% name = CGI.param('name') or 'Arthur Dent' %]
[% planet = CGI.param('planet') or 'Earth' %]
 Welcome [% name %] of planet [% planet %].

Plugins also have their own chapter, Chapter 6.

The final teaser that weíre going to show you is the MACRO directive. This allows you to provide simple names for more complex commands, as the following example shows:

[% MACRO header(title, author)
     IF name == 'Arthur Dent';
        INCLUDE arthur/header
          title = "Arthur Dent: $title";
     ELSE;
        INCLUDE guest/header
          title = "Guest User: $title";
     END;
%]

Donít worry if you canít make much sense of that now. The point that weíre illustrating is that sometimes Template Toolkit code can get quite complex. However, the MACRO directive allows you to define the complicated part in one place so that you can use a much simpler call to the macro in the rest of your templates:

[% header('Arthur Dent', 'My Home Page') %]

 

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 PROGRAMMING ARTICLES

- 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: