Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Perl Web Development - From Novice To Professional (2006)

.pdf
Скачиваний:
56
Добавлен:
17.08.2013
Размер:
2.9 Mб
Скачать

230 C H A P T E R 1 1 D E V E L O P M E N T W I T H M O D _ P E R L

In addition, consider exactly what you’re doing with mod_perl programs when working with the Apache request/response lifecycle and the Apache server itself. All of these things can introduce risk into programs if they are executed maliciously. For instance, writing to log files from a mod_perl program could result in an attacker filling up a disk with spurious log entries.

Finally, mod_perl inherits all of the risks present in CGI programs, such as possible attacks if input from forms isn’t properly sanitized. Refer to the earlier chapters on CGI programming (Chapters 1 through 4) for more information about those security considerations.

Summary

This chapter examined development with mod_perl. You learned about variable scoping with mod_perl, Apache::Registry, and the Apache request object. To appreciate the full power of mod_perl, I highly recommend working with it to perform more advanced programming and to increase the performance of your programs. The benefits of mod_perl for high-performance web sites are immense.

Looking ahead, the next chapter will shift gears once again and discuss templating with Perl. By using templates, you can increase your web design productivity. As you’ll see, Perl offers more than a few options for templating.

P A R T 5

■ ■ ■

Creating Web Templates

C H A P T E R 1 2

■ ■ ■

The Template Toolkit

Although templates don’t seem quite as fun as, say, programming a SOAP interface into the United States National Weather Service, they are actually quite interesting and they are definitely timesavers. I have yet to meet a Perl programmer who doesn’t like saving time; let the computer do the work.

In this chapter, you’ll examine the Template Toolkit in detail, and then concentrate on using the Template Toolkit to create and maintain a web site. But first, let’s briefly look at why Perl is ideal for use with templates.

Perl and Templates

Perl lends itself to the task of creation and completion of templates on many levels. Whether it’s plain text substitutions in plain text documents, PDFs, or HTML, Perl is an excellent language for working with templates, for the same reasons Perl is great for almost any task:

Perl is lightweight. There’s not much overhead required to create powerful programs.

Perl is easy to learn. You don’t have to work through idiotic and arcane syntax to make Perl programs do what you want them to.

Perl is widely supported. You can run Perl programs on many platforms and architectures.

These and a whole host of other reasons give Perl an advantage for templates and beyond. I currently use the Perl templating software Mason for my web site. Using Mason, I’m able to define a common header and footer for the site and have pages constructed on-the-fly using

those items. Mason works with mod_perl and integrates tightly into the process of serving web page. Mason will be covered in detail in Chapter 13.

Converting a site to Mason can be a little involved, and there are other well-implemented Perl packages for templating available. You’ll look at one such package, the Template Toolkit, next in this chapter. The Template Toolkit is easy to learn and offers a good way to get your feet wet with templating, to find out if you want to convert your site to Mason (or if you need to convert it to Mason!).

233

234 C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

Template Toolkit Introduction

The Template Toolkit is powerful template processing software for Perl that’s actually a combination of a number of packages. Far from being a one-hit wonder, the Template Toolkit is

a great multitasker (how’s that for mixing metaphors) that is able to work with HTML as well as other formats, such as XML and even PDF.

In this section, you’ll learn about templating with Perl through the Template Toolkit.

Template Toolkit Example

Templates are objects (think: documents) that enable copying or reuse of textual patterns containing a mix of dynamic, changing text, surrounded by static and unchanging text. You can think of a template as a classic form letter—for example, “Dear [Your Name Here], You have just won a million dollars!” A marketing company develops the main body of text, “You have just won a million dollars,” and plugs that into a document. The company then feeds the document through some template-processing software to substitute the “[Your Name Here]” part with someone’s actual name. The final version would (or should) read, “Dear Steve Suehring, You have just won a million dollars!”

This isn’t very far off from the Template Toolkit syntax. Changing the form letter to typical Template Toolkit syntax and filling it out a little more might look like this:

Dear [% recipient %],

You have just won a million dollars! To retrieve your million dollars, send your bank account information to [% scammer_address %]. I will require you to give me [% scam_amount %] so that I can get the funds.

Yours,

[% scammer_name %]

This text is saved to a file called templateexample.txt. Creating the end result letter with the Template Toolkit looks like this:

tpage --define recipient=Steve \

>--define scammer_name=Dan \

>--define scammer_address=dan@example.com \

>--define scam_amount=\$500 \

>templateexample.txt

The final letter is as follows:

Dear Steve,

You have just won a million dollars! To retrieve your million dollars, send your bank account information to dan@example.com. I will

require you to give me $500 so that I can get the funds.

Yours,

C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

235

The command tpage processes templates with the Template Toolkit on a file-by-file basis. This is in addition to the ttree command that processes templates on a per-directory basis. Both commands are covered in detail later.

The command shown to process the template first defines four variables: recipient, scammer_name, scammer_address, and scam_amount. Notice that the order of these definitions is not tied to the order in which they appear in the document, as scammer_name was used last in the document but defined second. The command then indicates which template to process— templateexample.txt, in this case.

When executed, the command prints to STDOUT. This could easily be shell redirected into a new file I’ll call letter.txt:

tpage --define recipient=Steve \ > --define scammer_name=Dan \

> --define scammer_address=dan@example.com \

> --define scam_amount=\$500 templateexample.txt > letter.txt

You’ve now seen a rudimentary example of what the Template Toolkit can do. The benefits you can reap from the Template Toolkit are directly related to the number of templates you can create for processing.

Considering specifically web site creation and maintenance, pages frequently have a common or usually common header and footer. Using the Template Toolkit, it’s possible to create that common header and footer, and feed the raw pages through ttree to create the site.

Beyond tpage and ttree, the Template Toolkit can plug directly into Apache through mod_perl with the help of the Apache::Template module. Using Apache::Template, it’s possible to create pages on-the-fly with the Template Toolkit. Apache::Template won’t be covered in much detail in this chapter but another on-the-fly web page creation module (Mason) will be covered in the next chapter.

Using the Template Toolkit

The Template Toolkit is a large and powerful application set. You can use the toolkit through several interfaces, including two programs (tpage and ttree), a Perl module, and an Apache module. This section begins by examining the interfaces that you’ll use to process templates through the Template Toolkit.

tpage

As you’ve seen already, the tpage program can be used to process a template where the name of the template is used as an argument. The output is sent to STDOUT. You can also send the output through a redirect to send it into a file, as was shown previously as well.

When using tpage to process a file, it’s common to use the --define option to define variables for substitution. This example was shown earlier and is repeated here for your reference:

tpage --define recipient=Steve \

>--define scammer_name=Dan \

>--define scammer_address=dan@example.com \

>--define scam_amount=\$500 templateexample.txt > letter.txt

236 C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

You can also call tpage without any arguments to use it in interactive mode. When using tpage in interactive mode, you’re required to enter both the variables and the text. A ^D indicates the end of input and the beginning of processing. From the command prompt, you type tpage, as in this example:

tpage

[% server = 'www' ip = '127.0.0.1'

%]

We noticed that your server, [% server %], at IP [% ip %], is currently down.

When you’re ready to process the template, press Ctrl+D (^D) to begin processing. Here’s the output you’ll see:

We noticed that your server, www, at IP 127.0.0.1, is currently down.

ttree

When updating a web site with the Template Toolkit, you’ll frequently use the ttree program. ttree operates on entire directories of files and offers much greater flexibility to the developer attempting to maintain a large web site through templates. ttree offers a huge number of options, compared with tpage, as shown in Listing 12-1.

Listing 12-1. Options Available with ttree

ttree 2.78 (Template Toolkit version 2.14)

usage: ttree [options] [files]

Options:

 

 

 

 

-a

(--all)

Process

all files, regardless of modification

-r

(--recurse)

Recurse

into sub-directories

 

-p

(--preserve)

Preserve file ownership and permission

-n

(--nothing)

Do nothing, just print summary (enables -v)

-v

(--verbose)

Verbose

mode

 

-h

(--help)

This help

 

-s DIR

(--src=DIR)

Source directory

 

-d DIR

(--dest=DIR)

Destination directory

 

-c DIR

(--cfg=DIR)

Location of configuration files

 

-l DIR

(--lib=DIR)

Library

directory (INCLUDE_PATH)

(multiple)

-f FILE

(--file=FILE)

Read named configuration file

(multiple)

File search specifications (all may

appear multiple times):

 

--ignore=REGEX

Ignore files matching REGEX

 

--copy=REGEX

Copy files matching REGEX

 

--accept=REGEX

Process

only files matching REGEX

 

C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

237

File Dependencies Options:

 

--depend foo=bar,baz

Specify that 'foo' depends on 'bar' and 'baz'.

--depend_file FILE

Read file dependencies from FILE.

--depend_debug

Enable debugging for dependencies

File suffix rewriting (may appear multiple times)

--suffix old=new

Change any '.old' suffix to '.new'

Additional options to set Template Toolkit configuration items:

--define var=value

Define template variable

--interpolate

Interpolate '$var' references in text

--anycase

Accept directive keywords in any case.

--pre_chomp

Chomp leading whitespace

--post_chomp

Chomp trailing whitespace

--trim

Trim blank lines around template blocks

--eval_perl

Evaluate [% PERL %] ... [% END %] code blocks

--load_perl

Load regular Perl modules via USE directive

--absolute

Enable the ABSOLUTE option

--relative

Enable the RELATIVE option

--pre_process=TEMPLATE

Process TEMPLATE before each main template

--post_process=TEMPLATE

Process TEMPLATE after each main template

--process=TEMPLATE

Process TEMPLATE instead of main template

--wrapper=TEMPLATE

Process TEMPLATE wrapper around main template

--default=TEMPLATE

Use TEMPLATE as default

--error=TEMPLATE

Use TEMPLATE to handle errors

--debug=STRING

Set TT DEBUG option to STRING

--start_tag=STRING

STRING defines start of directive tag

--end_tag=STRING

STRING defined end of directive tag

--tag_style=STYLE

Use pre-defined tag STYLE

--plugin_base=PACKAGE

Base PACKAGE for plugins

--compile_ext=STRING

File extension for compiled template files

--compile_dir=DIR

Directory for compiled template files

--perl5lib=DIR

Specify additional Perl library directories

--template_module=MODULE

Specify alternate Template module

See 'perldoc ttree' for further information.

Like tpage, ttree can have its execution controlled by combining these options on the command line. However, when working with ttree, it’s common to use a configuration file to hold information about the project, its file locations, and the behavior for ttree. Configuration files are typically created on a per-project basis and then either included on the command line for ttree or placed in the ttree run control file.

Controlling the execution of ttree is a run control (rc) file called .ttreerc, which is located in your home directory by default. The first time that you run ttree, you are presented with a prompt to create a sample configuration file:

Do you want me to create a sample '.ttreerc' file for you?

238 C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

I recommend entering a y to indicate that ttree should create the run control file. The default run control file contains some interesting bits of information, as shown in Listing 12-2.

Listing 12-2. Default Run Control File

#------------------------------------------------------------------------

# sample .ttreerc file created automatically by ttree version 2.78

#

#This file originally written to /home/suehring/.ttreerc

#For more information on the contents of this configuration file, see

#perldoc ttree

#ttree -h

#

#------------------------------------------------------------------------

#The most flexible way to use ttree is to create a separate directory

#for configuration files and simply use the .ttreerc to tell ttree where

#it is.

#

#cfg = /path/to/ttree/config/directory

#print summary of what's going on verbose

#recurse into any sub-directories and process files recurse

#regexen of things that aren't templates and should be ignored ignore = \b(CVS|RCS)\b

ignore = ^#

#ditto for things that should be copied rather than processed. copy = \.png$

copy = \.gif$

#by default, everything not ignored or copied is accepted; add 'accept'

#lines if you want to filter further. e.g.

#

#accept = \.html$

#accept = \.tt2$

#options to rewrite files suffixes (htm => html, tt2 => html)

#suffix htm=html

#suffix tt2=html

C H A P T E R 1 2 T H E T E M P L AT E TO O L K I T

239

#options to define dependencies between templates

#depend *=header,footer,menu

#depend index.html=mainpage,sidebar

#depend menu=menuitem,menubar

#------------------------------------------------------------------------

#The following options usually relate to a particular project so

#you'll probably want to put them in a separate configuration file

#in the directory specified by the 'cfg' option and then invoke tree

#using '-f' to tell it which configuration you want to use.

#However, there's nothing to stop you from adding default 'src',

#'dest' or 'lib' options in the .ttreerc. The 'src' and 'dest' options

#can be re-defined in another configuration file, but be aware that 'lib'

#options accumulate so any 'lib' options defined in the .ttreerc will

#be applied every time you run ttree.

#------------------------------------------------------------------------

## directory containing source page templates

#src = /path/to/your/source/page/templates

#

## directory where output files should be written

#dest = /path/to/your/html/output/directory

#

## additional directories of library templates

#lib = /first/path/to/your/library/templates

#lib = /second/path/to/your/library/templates

The items in this run control file are also used in a configuration file. Therefore, if you maintain only one site, you can leave the .ttreerc file as is. However, if you maintain more than one site with the Template Toolkit, you’ll likely want to create a minimal .ttreerc file and call individual ttree configuration files based on each project. You should do this because each ttree configuration file will hold information about files to ignore, directories to find the template files and to place the output files, and so on. Specifying the configuration file for ttree to use as part of its command line looks like this:

ttree -f /path/to/project-ttree.cfg

A Quick Look at ttree Options

When using ttree to create and manage a web site, it’s common to use certain directives and options. Some of those options are placed in the default .ttreerc file shown previously. This section looks briefly at a few of those options before they are discussed in detail later.

Since ttree operates on templates within a directory, you need to tell it where to find the source template files. Related to that, you also need to tell ttree where to place the destination or output files. The -s and -d command-line options specify the source and destination directories, respectively:

ttree -s sourcedir -d destdir