1. Trang chủ
  2. » Công Nghệ Thông Tin

OReilly perl template toolkit dec 2003 ISBN 0596004761

1,3K 59 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 1.305
Dung lượng 3,65 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

The following typographical conventions are used throughoutthis book: Constant width Used for Perl code, Template Toolkit directives, HTML, andcode examples.. Template Toolkit The Templa

Trang 2

walks you through generating and using data files, particularly with XML It also provides detailed information on the Template Toolkit's modules, libraries, and tools in addition to a complete reference manual.

Trang 6

Colophon

Index

Trang 7

Printed in the United States of America

Published by O'Reilly Media, Inc., 1005 Gravenstein HighwayNorth, Sebastopol, CA 95472

O'Reilly & Associates books may be purchased for educational,business, or sales promotional use Online editions are also

available for most titles (http://safari.oreilly.com) For moreinformation, contact our corporate/institutional sales

While every precaution has been taken in the preparation of thisbook, the publisher and authors assume no responsibility forerrors or omissions, or for damages resulting from the use ofthe information contained herein

Trang 8

Perl Template Toolkit is an introduction to the Template Toolkit.

The Template Toolkit is most often used in the creation of websites, but it can be used as a general text manipulation tool It

is a presentation management system that allows you to

separate aspects of presentation from the rest of an application,

in the same way that a database allows you to separate storageconcerns

The information in this book is based on Version 2.10 of theTemplate Toolkit, released in July 2003 The Template Toolkitwill continue to evolve Apart from bug fixes and minor updates,the Version 2.* branch will remain pretty much the same as it isnow

Version 3, expected sometime in 2004, will include new featuresand some changes to the internal architecture However, it is animportant requirement that new versions of the Template

Toolkit are backward-compatible with previous versions

wherever possible Although the Template Toolkit may change insome subtle ways, the basic principles, syntax, and style arehere to stay

Trang 9

This book should be useful to anyone building and maintainingweb sites or other complex content systems No prior

knowledge of Perl, the Template Toolkit, or HTML is required toapply the basic techniques taught in this book Some of themore advanced topics require some degree of familiarity withthe Perl programming language Readers who understand thebasic language constructs and idioms of Perl and who alreadyknow how to install and use Perl modules will have no troubleintegrating the Template Toolkit into their existing or new

projects Some chapters talk about more specific applicationareas: HTML, web programming, XML, and SQL, for example.Experience in these areas will make the benefits of the

Template Toolkit more readily apparent, but isn't required

Trang 10

Toolkit It gives a brief overview of many of the features of theTemplate Toolkit that are covered in more detail later in the

book

the Template Toolkit In this chapter, we look at the syntax ofthe Template Toolkit's presentation language

Plugins are another way to extend the Template Toolkit by

giving your templates access to powerful external modules Thischapter includes a guide to the various standard plugins that

Trang 11

put together everything we've covered in the previous chaptersand shows how to build a static web site using the TemplateToolkit

extends the example of the previous chapter to add dynamiccontent to your web site

Template Toolkit and Apache::Template

Trang 12

The following typographical conventions are used throughoutthis book:

Constant width

Used for Perl code, Template Toolkit directives, HTML, andcode examples

Italic

Used for filenames, URLs, hostnames, first use of terms,and emphasis

Indicates a tip, suggestion, or general note.

Indicates a warning or caution.

Trang 13

Please address comments and questions concerning this book tothe publisher:

bookquestions@oreilly.com

For more information about books, conferences, software,

Resource Centers, and the O'Reilly Network, see the O'Reillyweb site at:

http://www.oreilly.com

Trang 14

This book would not be possible without the contribution andsupport of many individuals, including friends, family, and thehard-working folks at O'Reilly & Associates, Inc All three of uswish to thank our production team and, in particular, our editor,Nathan Torkington, for his fine word wrangling and masterfulcat herding We would also like to thank our technical reviewersChris Devers, Mark Fowler, Andrew Langmead, Martin Portman,and Simon Matthews for their detailed and insightful comments

Andy Wardley

I'd like to start by thanking Dave, Darren, Nat, and the

production team at O'Reilly for turning a bunch of words into abook I would also like to thank Dom Millar for suggesting abadger for the front cover, and the design team for

accommodating us with this beautiful animal

The Template Toolkit has long since ceased to be a product of

my work alone, if indeed it ever was It owes its success to thededicated efforts of an extended team of developers, testers,documenters, and users At the time of this writing, the

Template Toolkit documentation lists over sixty contributors whohave donated their time and effort in different ways Our

collective thanks go to each of them: Chuck Adams, StephenAdkins, Ivan Adzhubey, Mark Anderson, Bradley Baetz, Thierry-Michel Barral, Craig Barratt, Stas Bekman, Tony Bowden, NeilBowers, Leon Brocard, Lyle Brooks, David Cantrell, Piers

Cawley, Darren Chamberlain, Eric Cholet, Dave Cross, ChrisDean, Francois Desarmenien, Horst Dumcke, Mark Fowler,

Michael Fowler, Axel Gerstmair, Dylan William Hardison, PerrinHarkins, Bryce Harrington, Dave Hodgkinson, Harald Joerg,

Colin Johnson, Vivek Khera, Rafael Kitover, Ivan Kurmanov,

Trang 15

Makepeace, Gervase Markham, Simon Matthews, Robert

McArthur, Craig McLane, Leslie Michael Orchard, Eugene

Miretskiy, Tatsuhiko Miyagawa, Keith G Murphy, Chris Nandor,Briac Pilpré, Martin Portman, Slaven Rezic, Christian Schaffner,Randal L Schwartz, Paul Sharpe, Ville Skyttä, Doug Steinwand,Michael Stevens, Drew Taylor, Swen Thuemmler, Richard

Tietjen, Stathy G Touloumis, Jim Vaughan, Simon Wilcox, andChris Winters

Special thanks are due to Simon Matthews, who has been usingand abusing the Template Toolkit and its predecessors from thevery start Countless pints of Guinness have been consumedthrough long evenings spent discussing the design,

development, and general direction of the project I would alsolike to thank Martin Portman for the many enjoyable hours wehave spent at the whiteboard, engaged in animated

conversation and frantic scribbling Many of the important TTdesign decisions have been thrashed out in the company ofSimon and Martin Their efforts and input continue to be

gratefully received

I would also like to thank all my other friends and colleagues ofpast and present at Knowledge Pool, Canon Research CentreEurope, and Fotango, many of whom are listed above Each ofthese organizations and the people within them have playedimportant roles in the evolution of the Template Toolkit

Finally I would like to thank my wife, Sheila, and son, Ben, fortheir love, patience, and understanding Writing this book ate

up far too much of the time that should have been spent withyou

Darren Chamberlain

I'd like to thank my wife and kids for their help and support,

Trang 16

Thanks to Boston.com for having the incredibly sane policy of

using the best tool for the job, which means letting me use theTemplate Toolkit for so many things; to Andrew Langmead,

Chris Devers, and Mike Melillo for proofreading, fact-checking,and putting up with me in general; and to Marc Lavallee, forintroducing me to TT in first place

Thanks to Andy for writing the Template Toolkit, which is as fineand versatile a piece of software as I've seen in a long time.Andy, Dave, and Nat have all been greatI hope I get to workthem again

And, of course, thanks to everyone who buys the book and

keeps O'Reilly (and their fine authors!) afloat

David Cross

I'd like to thank Andy for developing the Template Toolkit andboth Darren and Andy for making the process of writing thisbook as much fun as it was

Thanks to the members of the London.pm/TT cabal for first

introducing me to the Template Toolkit and convincing me that

it was the only templating system that I needed to look at

Thanks to the various clients and employers who have put upwith me leaving the office on time to get on with writing thebook Particular thanks should go to the people at Bibliotechwho took pity on me trying to write and work simultaneouslyand resolved the situation by making me redundant

Trang 17

them

Thank you to Joss Whedon for cancelling "Buffy the VampireSlayer" while I was working on this book and giving me one lessreason to avoid writing

Thank you to the various friends and family who have ensuredthat I still have a social life despite my seeming to do my

utmost to avoid it

Thanks, of course, to my parents Jean and John, and to my wifeGill Their love and support make it all much easier

Trang 18

Template Toolkit

The Template Toolkit is an all-Perl template processing system.Unlike many other Perl templating systems, it is as proficient atproducing HTML as it is at producing XML, PDF, or any otheroutput format It has its own simple templating language, sotemplates can be written and edited by people who do not knowPerl And it supports command-line, modular, CGI, and

mod_perl operation

In this chapter, we compare the Template Toolkit to other

templating systems such as HTML::Mason and HTML::Template,describe how to install it, then show you what templates looklike and how to process them The goal of this chapter is to getyou startedyou should be able to install the Template Toolkit,write and understand basic templates, and know how to processthe templates from the command line, from Perl programs, andfrom mod_perl

Trang 19

The basic task of a template processor is to output some

amount of changeable data surrounded by some unchangingdata A simple example of this is a form letter, where the sametext is sent to many different people, with just the name,

address, and other personal details being changed The

template contains the fixed ("boilerplate") text together withspecial markup tags indicating where the variable pieces of dataare to be placed

template is marked up using the default style of the TemplateToolkit, where the [% %] tags indicate variable values

Everything else is fixed text that passes through the processoruntouched

Trang 22

industry Or a Vogon Constructor Fleet

This book is a good example of a more complex template AllO'Reilly books conform to one of a small number of formats.They all have similar sets of front matter (title page, publicationinformation, table of contents, and preface), followed by theactual chapters, some (optional) appendices, an index, and

finally the colophon Templates that define the look of all of

these parts are defined in the publication system, and the datafor a particular book is formatted to conform to those rules Ifsomeone decides to change the font used for the chapter titles

in forthcoming books, he need only change the setting in thetemplate definition

Another way to look at a template processor is as a tool for

separating processing from presentation For example, a

company sales report is probably created from data stored in adatabase One way to create the report would be to extract therequired data into a spreadsheet and then do calculations onthe data to produce the information required The spreadsheetcould then be printed out or emailed to the required recipients

Although you can use templates to generate any kind of textdocument, the most common use is to generate HTML pages forweb content The whole genre of template processing systemshas matured rapidly in less than a decade, particularly withinthe Perl community, in response to the demands of people

struggling to build and maintain ever more complex content andapplications for their web sites

Templates help in a number of ways The most obvious benefit

is that they can be used to apply a consistent look and feel toall the pages in a web site to achieve a common branding Youcan use a template to add standard headers, footers, menus,and other user interface components as easily as the

Hyperspace Planning Council ruthlessly adds a few lines of

Vogon poetry to every planet destruction order, just to rub salt

Trang 23

This is just the tip of the iceberg In addition to the use of

variables, the Template Toolkit provides a number of other

directives that instruct it to perform more complex processingactions, such as including another template, repeating a section

of markup for different pieces of data, or choosing a section toprocess based on a particular condition Example 1-3 illustratessome of these directives in action

Example 1-3 Loops, conditions, and processing instructions in a template

Trang 24

nonprogrammers to use it without first having to get to gripswith Perl The Template Toolkit provides language features and

Trang 25

If you do know Perl, however, you'll be able to get more out ofthe Template Toolkit by writing custom functions and extensions

to handle the specifics of your particular application The goodnews for Perl programmers is that the Template Toolkit allowsyou to separate Perl code clearly from HTML templates Thisclear separation means that you don't have to wade throughpages of HTML markup to find the part of your web applicationthat needs attention It allows you to concentrate on one thing

at a time, be it the HTML presentation or the Perl application,without having the other aspects in your face and under yourfeet It makes both your HTML templates and Perl code moreportable and reusable, and easier to read, write, and maintain

Trang 26

At least half a dozen mature and respected templating systemsare available for Perl The best-known and best-supported

HTML-like tags, and enforces the divide between design andprogramming by restricting what a template is capable ofdoing By limiting the programmer to using just simple

variables and loops in the HTML, the template remains

Trang 27

and can call each other and pass values back and forth likesubroutines Components increase modularity and eliminaterepetitive work: common design elements (headers,

footers, menus, logos) can be extracted into their own

components where they need be changed only once to

affect the whole site Mason also includes powerful filteringand templating facilities and an HTML/data caching model

HTML::Mason is available from http://www.masonhq.com/

and CPAN (http://search.cpan.org/dist/HTML-Mason/)

HTML::Embperl

Embperl gives you the power to embed Perl code in yourHTML documents, and the ability to build your web site out

of small reusable objects in an object-oriented style Youcan also take advantage of all the usual Perl modules

(including DBI for database access), use their functionality,and easily include their output in your web pages

Embperl has several features that are especially useful forcreating HTML, including dynamic tables, form field

Trang 28

Embperl is a server-side tool, which means that it's

browser-independent It can run in various ways: undermod_perl, as a CGI script, or offline

HTML::Embperl is available from http://www.ecos.de/ orCPAN (http://search.cpan.org/dist/HTML-Embperl/)

Apache::ASP

Apache::ASP provides an Active Server Pages port to theApache web server with Perl scripting only, and enables

development of dynamic web applications with session

management and embedded Perl code Apache::ASP alsoprovides many powerful extensions, including XML taglibs,XSLT rendering, and new events not originally part of theASP API

Apache::ASP is available from CPAN

The Template Toolkit attempts to offer the best features of

these modules, including separation of Perl from templates andapplicability beyond HTML

1.2.1 The Template Toolkit Is for More Than

HTML

The Template Toolkit is a generic template processing systemthat will process any kind of document for use in any

environment or application Many other template systems weredesigned specifically to create HTML pages for web content In

Trang 29

1.2.2 The Template Toolkit Lets You Choose Your Separation

Template Toolkit doesn't prescribe any particular methodology

or framework that forces you to use it in a certain way Somemodules (for example, HTML::Template) enforce a very strictinterpretation of template processing that intentionally limitswhat can be done in a template to accessing variables and

using simple conditional or looping constructs Others (such as

HTML::Mason and HTML::Embperl) use embedded Perl code toallow any kind of application functionality to be incorporateddirectly into the templates

The Template Toolkit gives you the best of both worlds It has a

powerful data engine (the Stash) that does all the hard work of

mapping complex data structures from your Perl code,

configuration files, SQL databases, XML files, and so on, intotemplate variables that are accessed by a simple and uniformdotted notation (e.g., person.surname) You can use this tokeep your templates simple without limiting the complexity orfunctionality of the systems that put data into the templates

At the opposite end of the spectrum, the Template Toolkit alsoallows you to embed Perl code directly in your templates We

Trang 30

place Because this is the exception rather than the norm,

template processors must set the EVAL_PERL option to embedPerl code in the template (it is disabled by default) We look athow to set options later in this chapter

$person->{surname} # Perl

person.surname # Template Toolkit

This hides the underlying implementation details from the

template designer In the previous example, the Perl syntaximplies that $person is a reference to a hash array containing a

Trang 31

confusing syntax and can concentrate on the task at hand ofpresenting the data nicely This makes the template language

1.2.4 The Template Toolkit Is Easy to Extend

The Template Toolkit is designed to be easy to extend If it

doesn't already do what you want, there's a good chance youcan reimplement a small part of it to change it to do what youwhat The object-oriented architecture of the Template Toolkitmakes this process relatively straightforward, and there are

Trang 32

A number of plugins exist for the Template Toolkit, and we

cover them in Chapter 6 They are designed to give templatesconvenient control over things such as HTML tables, databaseconnections, and CGI parameters

Trang 33

At any one time you can download from the Web at least twopossible versions of the Template Toolkit: a stable version and adeveloper version The stable version has a version numbersuch as 2.10, and has been widely tested before release Thedeveloper versions have version numbers such as 2.10a, andtypically have bug fixes and early implementations of new

features Generally, you should install the latest stable release

1.3.1 Downloading

The Template Toolkit is available from the Comprehensive PerlArchive Network (CPAN) You can always download the mostrecent stable version of the Template Toolkit from

Manager)

You can also get developer versions of the Template Toolkit

from the web site Normally, you need to download only thecurrent stable version, but if you come across a bug that isn'tfixed in the CPAN version, you may need to use a developerrelease

If a developer release isn't cutting-edge enough for you, theweb site contains information on how to get access to the CVS

Trang 34

Template Toolkit source code are kept If you want to add

functionality to the Template Toolkit or have found a bug thatyou can fix, and you want your patch to be accepted by

controlled by arguments to perl Makefile.PL Run perl

Trang 37

The README and INSTALL files in the Template Toolkit

distribution directory provide further information about runningthe test suite and what to do if something goes wrong

Trang 38

In this section, we take a look at the support that is availablefor the Template Toolkit

1.4.1 Viewing the Documentation

The Template Toolkit comes with an incredible amount of

documentation The documentation is supplied in the standardPerl Plain Old Documentation (POD) format Once you have

might put the contents of Example 1-4 in the httpd.conf for an

Apache web server

Example 1-4 Apache configuration directives to view Template Toolkit documentation

Trang 39

The complete documentation set is also available online at theTemplate Toolkit web site You can find it at

1.4.2 Overview of the Documentation

A large number of manual pages come with the Template

Toolkit Here is a list of some of the most useful ones:

Ngày đăng: 26/03/2019, 17:09

TỪ KHÓA LIÊN QUAN