This is Info file pm.info, produced by Makeinfo version 1.68 from the input file bigpm.texi.  File: pm.info, Node: Text/SimpleTemplate, Next: Text/Soundex, Prev: Text/Shoebox, Up: Module List Yet another module for template processing ****************************************** NAME ==== Text::SimpleTemplate - Yet another module for template processing SYNOPSIS ======== use Text::SimpleTemplate; $tmpl = new Text::SimpleTemplate; # create processor object $tmpl->setq(TEXT => "hello, world"); # export data to template $tmpl->load($file); # loads template from named file $tmpl->pack(q{TEXT: <% $TEXT; %>}); # loads template from in-memory data print $tmpl->fill; # prints "TEXT: hello, world" DESCRIPTION =========== This is yet another library for template-based text generation. Template-based text generation is a way to separate program code and data, so non-programmer can control final result (like HTML) as desired without tweaking the program code itself. By doing so, jobs like website maintenance is much easier because you can leave program code unchanged even if page redesign was needed. The idea is simple. Whenever a block of text surrounded by '<%' and '%>' (or any pair of delimiters you specify) is found, it will be taken as Perl expression, and will be replaced by its evaluated result. Major goal of this library is simplicity and speed. While there're many modules for template processing, this module has near raw Perl-code (i.e., "s|xxx|xxx|ge") speed, while providing simple-to-use objective interface. INSTALLATION / REQUIREMENTS =========================== This module requires Carp.pm and FileHandle.pm. Since these are standard modules, all you need is perl itself. For installation, standard procedure of perl Makefile.PL make make test make install should work just fine. TEMPLATE SYNTAX AND USAGE ========================= Suppose you have a following template named "sample.tmpl": === Module Information === Name: <% $INFO->{Name}; %> Description: <% $INFO->{Description}; %> Author: <% $INFO->{Author}; %> <<% $INFO->{Email}; %>> With the following code... use Safe; use Text::SimpleTemplate; $tmpl = new Text::SimpleTemplate; $tmpl->setq(INFO => { Name => "Text::SimpleTemplate", Description => "Yet another module for template processing", Author => "Taisuke Yamada", Email => "tai\@imasy.or.jp", }); $tmpl->load("sample.tmpl"); print $tmpl->fill(PACKAGE => new Safe); ...you will get following result: === Module Information === Name: Text::SimpleTemplate Description: Yet another module for template processing Author: Taisuke Yamada As you might have noticed, any scalar data can be exported to template namespace, even hash reference or code reference. By the way, although I used "Safe" module in example above, this is not a requirement. However, if you want to control power of the template editor over program logic, its use is strongly recommended (see *Note Safe: Safe, for more). DIRECT ACCESS TO TEMPLATE NAMESPACE =================================== In addition to its native interface, you can also access directly to template namespace. $FOO::text = 'hello, world'; @FOO::list = qw(foo bar baz); $tmpl = new Text::SimpleTemplate; $tmpl->pack(q{TEXT: <% $text; %>, LIST: <% "@list"; %>}); print $tmpl->fill(PACKAGE => 'FOO'); While I don't recommend this style, this might be useful if you want to export list, hash, or subroutine directly without using reference. METHODS ======= Following methods are currently available. $tmpl = Text::SimpleTemplate->new; Constructor. Returns newly created object. If this method was called through existing object, cloned object will be returned. This cloned instance inherits all properties except for internal buffer which holds template data. Cloning is useful for chained template processing. $tmpl->setq($name => $data, $name => $data, ...); Exports scalar data ($data) to template namespace, with $name as a scalar variable name to be used in template. You can repeat the pair to export multiple sets in one operation. $tmpl->load($file, %opts); Loads template file ($file) for later evaluation. File can be specified in either form of pathname or fileglob. This method accepts DELIM option, used to specify delimiter for parsing template. It is speficied by passing reference to array containing delimiter pair, just like below: $tmpl->load($file, DELIM => [qw()]); Returns object reference to itself. $tmpl->pack($data, %opts); Loads in-memory data ($data) for later evaluation. Except for this difference, works just like $tmpl->load. $text = $tmpl->fill(%opts); Returns evaluated result of template, which was preloaded by either $tmpl->pack or $tmpl->load method. This method accepts two options: PACKAGE and OHANDLE. PACKAGE option specifies the namespace where template evaluation takes place. You can either pass the name of the package, or the package object itself. So either of $tmpl->fill(PACKAGE => new Safe); $tmpl->fill(PACKAGE => new Some::Module); $tmpl->fill(PACKAGE => 'Some::Package'); works. In case Safe module (or its subclass) was passed, its "reval" method will be used instead of built-in eval. OHANDLE option is for output selection. By default, this method returns the result of evaluation, but with OHANDLE option set, you can instead make it print to given handle. Either style of $tmpl->fill(OHANDLE => \*STDOUT); $tmpl->fill(OHANDLE => new FileHandle(...)); is supported. NOTES / BUGS ============ Nested template delimiter will cause this module to fail. CONTACT ADDRESS =============== Please send any bug reports/comments to . AUTHORS / CONTRIBUTORS ====================== - Taisuke Yamada - Lin Tianshan COPYRIGHT ========= Copyright 1999-2001. All rights reserved. This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.  File: pm.info, Node: Text/Soundex, Next: Text/Striphigh, Prev: Text/SimpleTemplate, Up: Module List Implementation of the Soundex Algorithm as Described by Knuth ************************************************************* NAME ==== Text::Soundex - Implementation of the Soundex Algorithm as Described by Knuth SYNOPSIS ======== use Text::Soundex; $code = soundex($name); # Get the soundex code for a name. @codes = soundex(@names); # Get the list of codes for a list of names. # This is how you define what you want to be returned if your # input string has no indentifiable codes within it. # Make the change permanent. $Text::Soundex::nocode = 'Z000'; # Make the change temporary. { local $Text::Soundex::nocode = 'Z000'; # Temporary change. $code = soundex($name); } DESCRIPTION =========== This module implements the soundex algorithm as described by Donald Knuth in Volume 3 of *The Art of Computer Programming*. The algorithm is intended to hash words (in particular surnames) into a small space using a simple model which approximates the sound of the word when spoken by an English speaker. Each word is reduced to a four character string, the first character being an upper case letter and the remaining three being digits. The value returned for strings which have no soundex encoding is set in the scalar `$Text::Soundex::nocode'. This is initially set to undef, but many people seem to prefer an *unlikely* value like `Z000' (how unlikely this is depends on the data set being dealt with.) Any value can be assigned to `$Text::Soundex::nocode'. For backward compatibility with older versions of this module the `$Text::Soundex::nocode' is exported into the caller's namespace as `$soundex_nocode'. In scalar context soundex returns the soundex code of its first argument, and in array context a list is returned in which each element is the soundex code for the corresponding argument passed to soundex e.g. @codes = soundex qw(Mike Stok); leaves `@codes' containing `('M200', 'S320')'. If you wish to use Text::Soundex for searching for your name in one of the US Censuses made publicly available, you must instruct the module of your intentions by doing one of the following: # First method: use Text::Soundex qw(:NARA-Ruleset); $code = soundex($name); # Second method: use Text::Soundex qw(soundex_nara); $code = soundex_nara($name); This is necessary, as the algorithm used by the US Censuses is slightly different than that defined by Knuth and others. The descrepancy can be shown using the name "Ashcraft": print soundex("Ashcraft"), "\n"; # prints: A226 print soundex_nara("Ashcraft"), "\n"; # prints: A261 Their is also a speed hit involved when using the NARA ruleset. (The encoding is slightly more complicated) EXAMPLES ======== Knuth's examples of various names and the soundex codes they map to are listed below: Euler, Ellery -> E460 Gauss, Ghosh -> G200 Hilbert, Heilbronn -> H416 Knuth, Kant -> K530 Lloyd, Ladd -> L300 Lukasiewicz, Lissajous -> L222 so: $code = soundex 'Knuth'; # $code contains 'K530' @list = soundex qw(Lloyd Gauss); # @list contains 'L300', 'G200' UNDERNEATH THE COVERS (a word from Mark) ======================================== To ease use for the user, the XS version is transparently accessible via soundex() when it exists for the current platform. Basically what this means is that if you are on a platform with XS code compiled, the call to soundex() will complete about 7X faster. If for whatever reason you care, and you want to choose which code to use, I have provided access to the individual calls. # The following calls are split up by functionality. # Always uses the 100% perl version. ... = Text::Soundex::soundex_noxs(...); # Always uses the XS version. (7X faster) ... = Text::Soundex::soundex_xs(...); # Use the XS version if possible, otherwise # it will revert to the 100% perl version. ... = Text::Soundex::soundex(...); =head1 LIMITATIONS As the soundex algorithm was originally used a long time ago in the US it considers only the English alphabet and pronunciation. As it is mapping a large space (arbitrary length strings) onto a small space (single letter plus 3 digits) no inference can be made about the similarity of two strings which end up with the same soundex code. For example, both `Hilbert' and `Heilbronn' end up with a soundex code of `H416'. AUTHOR ====== This code was originally implemented by Mike Stok (`mike@stok.co.uk') as an example of unreadable perl 4 code and refined into a library. The code is now maintained by Mark Mielke who recast the code and made it speedy in 1997. Mark has since added the XS code to accomplish the encoding at a speed upwards of 7X faster. Please report any bugs or other to Mark Mielke . Ian Phillips (`ian@pipex.net') and Rich Pinder (`rpinder@hsc.usc.edu') supplied ideas and spotted mistakes for v1.x. Dave Carlson (`dcarlsen@csranet.com') made the request for the NARA ruleset to be included. The ruleset is named "NARA", as the descrepancy was discovered due to the fact that it was the NARA soundex machine that was producing "invalid" codes in certain cases. The NARA soundex page can be viewed at: `http://www.nara.gov/genealogy/soundex/soundex.html'  File: pm.info, Node: Text/Striphigh, Next: Text/Structured, Prev: Text/Soundex, Up: Module List Perl extension to strip the high bit off of ISO-8859-1 text. ************************************************************ NAME ==== Text::Striphigh - Perl extension to strip the high bit off of ISO-8859-1 text. SYNOPSIS ======== use Text::Striphigh 'striphigh' $SevenBitsText = striphigh($TextContainingEightBitCharacters); DESCRIPTION =========== The Text::Striphigh module exports a single function: `striphigh'. This function takes one argument, a string possibly containing high ASCII characters in the ISO-8859-1 character set, and transforms this into a string containing only 7 bits ASCII characters, by substituting every high bit character with a similar looking standard ASCII character, or with a sequence of standard ASCII characters. Because of precisely the deficiency this package tries to offer a workaround for is present in some of the things that process pod, there are no examples in this manpage. Look at the source or the test script if you want examples. MAINTENANCE =========== If you ever want to change the striphigh function yourself, then don't change the one containing the mile long `tr{}{}' statement that you see at first, change the one behind the `__DATA__' that's a lot more readable. After you've done that, simply run the `Striphigh.pm' file through perl to generate a new version of the first routine, and in fact of the entire file, something like this: perl -w Striphigh.pm > Striphigh.pm.new mv Striphigh.pm.new Striphigh.pm BUGS ==== Assumes the input text is ISO-8859-1, without even looking at the LOCALE settings. Some translations are probably less than optimal. People will be offended if you run their names through this function, and print the result on an envelope using an outdated printing device. However, it's probably better than having that printer print a name with a high ASCII character in it which happens to be the command to set the printer on fire. AUTHOR ====== Jan-Pieter Cornet  File: pm.info, Node: Text/Structured, Next: Text/StructuredBase, Prev: Text/Striphigh, Up: Module List Manipulate fixed-format pages ***************************** NAME ==== Text::Structured - Manipulate fixed-format pages SYNOPSIS ======== use Text::Structured; $st = new Text::Structured($page); $foo = $st->get_text_at($r,$c,$len); $foo = $st->get_text_re($r,$re); DESCRIPTION =========== *Text::Structured* is a class for manipulating fixed-format pages of text. A page is treated as a series of rows and columns with the row and column of the top left hand corner of the page being (0,0). SUPERCLASSES ============ *Text::StructuredBase* CLASS METHODS ============= new($page) ---------- Create a new *Text::Structured* object. $page is a string containing a page of text. OBJECT METHODS ============== get_text_at($r,$c,$len) ----------------------- Returns a substring of length *$len* starting at row $r, column $c. This method will die() if $r < 0 or $r > the number of lines in the page. See also `substr()', *Note Perlfunc: (perl.info)perlfunc,. get_text_re($r,$re) ------------------- Returns a string which is the result of applying the regular expression *$re* to row $r of the page. This method will die() if $r < 0 or $r > the number of lines in the page. do_method() ----------- This method can be used with the *Text::FillIn* module (available from CPAN) to fill a template using methods from *Text::Structured* e.g. use Text::FillIn; use Text::Structured; $page = q{foo bar baz quux}; $st = new Text::Structured($page); # set delimiters Text::FillIn->Ldelim('(:'); Text::FillIn->Rdelim(':)'); $template = new Text::FillIn; $template->object($st); $template->hook('&','do_method'); $template->set_text(q{Oh (:&get_text_at(0,0,3):), it's a (:&get_text_re(1,(\w+)$):)!}); $foo = $template->interpret; print "$foo\n"; Prints 'Oh foo, it's a quux!'. AUTHOR ====== Paul Sharpe COPYRIGHT ========= Copyright (c) 1999 Paul Sharpe. England. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.  File: pm.info, Node: Text/StructuredBase, Next: Text/Tabs, Prev: Text/Structured, Up: Module List Structured text base class ************************** NAME ==== Text::StructuredBase - Structured text base class SYNOPSIS ======== use base qw/Text::StructuredBase/; $object->debug($n); DESCRIPTION =========== *Text::StructuredBase* acts as a base class for *Text::Structured*. BASE CLASS METHODS ================== AUTOLOAD() ---------- AUTOLOAD() provides default accessor methods (apart from DESTROY()) for any of its subclasses. For AUTOLOAD() to catch calls to these methods objects must be implemented as an anonymous hash. Object attributes must * have UPPER CASE names * have keys in attribute _PERMITTED (an anonymous hash) The name accessor method is the name of the attribute in *lower case*. The 'set' versions of these accessor methods require a single scalar argument (which could of course be a reference.) Both 'set' and 'get' versions return the attribute's value. *Special Attributes* /_L$/ Attribute names matching the pattern /_L$/ will be treated as arrayrefs. These accessors require an arrayref as an argument. If the attribute is defined they return the arrayref, otherwise they return an empty arrayref. A method **_l_add(@foo)* can be called on this type of attribute to add the elements in *@foo* to the array. If the attribute is defined they return the arrayref, otherwise they return an empty arrayref. /_H$/ Attribute names matching the pattern /_H$/ will be treated as hashrefs. These accessors require a reference to an array containing key/value pairs. If the attribute is defined they return the hashref, otherwise they return an empty hashref. A method **_h_byname(@list)* can be called on this type of attribute. These methods will return a list which is the hash slice of the *_H* attribute value over *@list* or an empty list if the attribute is undefined. A method **_h_add(\%foo)* can be called on this type of attribute to add the elements in *%foo* to the hash. If the attribute is defined they return the hashref, otherwise they return an empty hashref. debug($n) --------- As a class method sets the class attribute *$Debugging* to $n. As an object method sets the object attribute *$_DEBUG* to $n. AUTHOR ====== Paul Sharpe COPYRIGHT ========= Copyright (c) 1999 Paul Sharpe. England. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.  File: pm.info, Node: Text/Tabs, Next: Text/TagTemplate, Prev: Text/StructuredBase, Up: Module List expand and unexpand tabs per the unix expand(1) and unexpand(1) *************************************************************** NAME ==== Text::Tabs - expand and unexpand tabs per the unix expand(1) and unexpand(1) SYNOPSIS ======== use Text::Tabs; $tabstop = 4; @lines_without_tabs = expand(@lines_with_tabs); @lines_with_tabs = unexpand(@lines_without_tabs); DESCRIPTION =========== Text::Tabs does about what the unix utilities expand(1) and unexpand(1) do. Given a line with tabs in it, expand will replace the tabs with the appropriate number of spaces. Given a line with or without tabs in it, unexpand will add tabs when it can save bytes by doing so. Invisible compression with plain ascii! BUGS ==== expand doesn't handle newlines very quickly - do not feed it an entire document in one string. Instead feed it an array of lines. AUTHOR ====== David Muir Sharnoff  File: pm.info, Node: Text/TagTemplate, Next: Text/Template, Prev: Text/Tabs, Up: Module List Text::TagTemplate ***************** NAME ==== Text::TagTemplate VERSION ======= $Revision: 1.4 $ SYNOPSIS ======== use Text::TagTemplate qw( :standard ); # Define a single tag to substitute in a template. add_tag( MYTAG => 'Hello world.' ); # Define several tags all at once. The tags() method wipes out # all current tags. tags( +{ FOO => 'The string foo.', # Single-quoted string BAR => "$ENV{ USER }", # Double-quoted string LIST => join( '
  • ', @list ), # Function call # Functions or subroutines that get called each time # the tag is replaced, possibly producing different # results for the same tag if it appears twice or more. TIME => \&time(), # Reference to a function SUB => sub { # Anonymous subroutine my( $params ) = @_; return $params->{ NAME }; } } ); # Add a couple of tags to the existing set. Takes a hash-ref. add_tags( +{ TAG1 => "Hello $ENV{ USER }", TAG2 => rand( 10 ), # random number between 0 and 10 } ); # Set the template file to use. template_file( 'template.htmlt' ); # This is list of items to construct a list from. list( 'One', 'Two', 'Three' ); # These are template-fragment files to use for making the list. entry_file( 'entry.htmlf' ); join_file( 'join.htmlf' ); # This is a callback sub used to make the tags for each entry in a # parsed list. entry_callback( sub { my( $item ) = @_; return +{ ITEM => $item }; } ); # Add a new tag that contains the whole parsed list. add_tag( LIST => parse_list_files ); # Print the template file with substitutions. print parse_file; DESCRIPTION =========== This module is designed to make the process of constructing web-based applications (such as CGI programs and Apache::Registry scripts) much easier, by separating the logic and application development from the HTML coding, and allowing ongoing changes to the HTML without requiring non-programmers to modify HTML embedded deep inside Perl code. This module provides a mechanism for including special HTML-like tags in a file (or scalar) and replacing those tags at run-time with dynamically generated content. For example the special tag <#USERINFO FIELD="favorite_color"> might be replaced by "green" after doing a database lookup. Usually each special tag will have its own subroutine which is executed every time the tag is seen. Each subroutine can be basically anything you might want to do in Perl including database lookups or whatever. You simply create subroutines to return whatever is appropriate for replacing each special tag you create. Attributes in the special tags (such as the FIELD="favorite_color" in the example above) are passed to the matching subroutine. It is not web-specific, though, despite the definite bias that way, and the template-parsing can just as easily be used on any other text documents. The examples here will assume that you are using it for convential CGI applications. It provides functions for parsing strings, and constructing lists of repeated elements (as in the output of a search engine). It is object-oriented, but - like the CGI module - it does not require the programmer to use an OO interface. You can just import the ":standard" set of methods and use them with no object reference, and it will create and use an internal object automatically. This is the recommended method of using it unless you either need multiple template objects, or you are concerned about namespace pollution. TEMPLATES ========= The structure of templates is as any other text file, but with extra elements added that are processed by the CGI as it prints the file to the browser. These extra elements are referred to in this manual as "tags", which should not be confused with plain HTML tags - these tags are replaced before the browser even begins to process the HTML tags. The syntax for tags intentionally mimics HTML tags, though, to simplify matters for HTML-coders. A tag looks like this: <#TAG> or optionally with parameters like: <#TAG NAME=VALUE> or with quoted parameters like: <#TAG NAME="Value, including spaces etc."> The tag name is the first part after the opening <# of the whole tag. It must be a simple identifier - I recommend sticking to the character set [A-Z_] for this. The following parameters are optional and only used if the tag-action is a callback subroutine (see below). They are supplied in HTML-style name/value pairs. The parameter name like the tag name must be a simple identifier, and again I recommend that it is drawn from the character set [A-Z_]. The value can be any string, quoted if it contains spaces and the like. Even if quoted, it may not contain any of: < > " & = which should be replaced with their HTML escape equivalents: < > " & = This may be a bug. At present, other HTML escapes are not permitted in the value. This may also be a bug. Tag names and parameter names are, by default, case-insensitive (they are converted to upper-case when supplied). You can change this behaviour by using the auto_cap() method. I don't recommend doing that, though. There are four special parameters that can be supplied to any tag, HTMLESC and URLESC. Two of them cause the text returned by the tag to be HTML or URL escaped, which makes outputting data from plain-text sources like databases or text files easier for the programmer. An example might be: <#FULL_NAME HTMLESC> which would let the programmer simply put the full-name data into the tag without first escaping it. Another might be: A typical template might look like: A template

    This is a tag: <#TAG>

    This is a list:

    <#LIST>

    This is a tag that calls a callback: <#ITEM ID=358>

    Note that it is a full HTML document. TAGS ==== You can supply the tags that will be used for substitutions in several ways. Firstly, you can set the tags that will be used directly, erasing all tags currently stored, using the tags() method. This method - when given an argument - removes all present tags and replaces them with tags drawn from the hash-reference you must supply. For example: tags( +{ FOO => 'A string called foo.', BAR => 'A string called bar.' } ); The keys to the hash-ref supplied are the tag names; the values are the substitution actions (see below for more details on actions). If you have an existing hash you can use it to define several tags. For example: tags( \%ENV ); would add a tag for each environment variable in the %ENV hash. Secondly, you can use the add_tags() method to add all the tags in the supplied hash-ref to the existing tags, replacing the existing ones where there is conflict. For example: add_tags( +{ FOOBAR => 'A string called foobar added.', BAR => 'This replaces the previous value for BAR' } ); Thirdly, you can add a single tag with add_tag(), which takes two arguments, the tag name and the tag value. For example: add_tag( FOO => 'This replaces the previous value for FOO' ); Which one of these is the best one to use depends on your application and coding style, of course. ACTIONS ======= Whichever way you choose to supply tags for substitutions, you will need to supply an action for each tag. These come in two sorts: scalar values (or scalar refs, which are treated the same way), and subroutine references for callbacks. Scalar Text Values ------------------ A scalar text value is simply used as a string and substituted in the output when parsed. All of the following are scalar text values: tags( +{ FOO => 'The string foo.', # Single-quoted string BAR => "$ENV{ USER }", # Double-quoted string LIST => join( '
  • ', @list ), # Function call } ); Subroutine References --------------------- If the tag action is a subroutine reference then it is treated as a callback. The value supplied to it is a single hash-ref containing the parameter name/value pairs supplied in the tag in the template. For example, if the tag looked like: <#TAG NAME="Value"> the callback would have an @_ that looked like: +{ NAME => 'Value' } The callback must return a simple scalar value that will be substituted in the output. For example: add_tag( TAG => sub { my( $params ) = @_; my $name = $params->{ NAME }; my $text = DatabaseLookup("$name"); return $text; } } ); You can use these callbacks to allow the HTML coder to look up data in a database, to set global configuration parameters, and many other situations where you wish to allow more flexible user of your templates. For example, the supplied value can be the key to a database lookup and the callback returns a value from the database; or it can be used to set context for succeeding tags so that they return different values. This sort of thing is tricky to code but easy to use for the HTMLer, and can save a great deal of future coding work. Default Action -------------- If no action is supplied for a tag, the default action is used. The default default action is to die() with an error, since usually the use of unknown tags indicates a bug in the application. You may wish to simply ignore unknown tags and replace them with blank space, in which case you can use the unknown_action() method to change it. If you wish to ignore unknown tags, you set this to the special value "IGNORE". For example: unknown_action( 'IGNORE' ); Unknown tags will then be left in the output (and typically ignored by web browsers.) The default action is indicated by the special value "DIE". If you want to have unknown tags just be replaced by warning text (and be logged with a warn() call), use the special value "WARN". For example: unknown_action( 'WARN' ); If the default action is a subroutine reference then the name of the unknown tag is passed as a parameter called "TAG". For example: unknown_action( sub { my( $params ) = @_; my $tagname = $params->{ TAG }; return "$tagname is unknown."; } ); You may also specify a custom string to be substituted for any unknown tags. For example: unknown_action( '***Unknown Tag Used Here***' ); PARSING ======= Once you have some tags defined by your program you need to specify which template to parse and replace tags in. You can supply a string to parse, or the name of file to use. The latter is usually easier. For example: template_string( 'A string containing some tag: <#FOO>' ); or: template_file( 'template.htmlt' ); These methods just set the internal string or file to look for; the actual parsing is done by the parse() or parse_file() methods. These return the parsed template, they don't store it internally anywhere, so you have to store or print it yourself. For example: print parse_file; will print the current template file using the current set of tags for substitutions. Or: $parsed = parse; will put the parsed string into $parsed using the current string and tags for substitutions. These methods can also be called using more parameters to skip the internally stored strings, files, and tags. See the per-method documentation below for more details; it's probably easier to do it the step-by-step method, though. MAKING LISTS ============ One of the things that often comes up in CGI applications is the need to produce a list of results - say from a search engine. Because you don't necessarily know in advance the number of elements, and usually you want each element formatted identically, it's hard to do this in a single template. This module provides a convenient interface for doing this using two templates for each list, each a fragment of the completed list. The "entry" template is used for each entry in the list. The "join" template is inserted in between each pair of entries. You only need to use a "join" template if you, say, want a dividing line between each entry but not one following the end of the list. The entry template is the interesting one. There's a complicated way of making a list tag and an easy way. I suggest using the easy way. Let's say you have three items in a list and each of them is a hashref containing a row from a database. You also have a file with a template fragment that has tags with the same names as the columns in that database. To make a list using three copies of that template and add it as a tag to the current template object, you can do: add_list_tag( ITEM_LIST => \@list ); and then when you use the tag, you can specify the template file in a parameter like this: <#ITEM_LIST ENTRY_FILE="entry.htmlf"> If the columns in the database are "name", "address" and "phone", that template might look like:
  • Name: <#NAME HTMLESC>
    Address: <#ADDRESS HTMLESC>
    Phone: <#PHONE HTMLESC
  • Note that the path to the template can be absolute or relative; it can be any file on the system, so make sure you trust your HTML people if you use this method to make a list tag for them. The second argument to add_list_tag is that list of tag hashrefs. It might look like: +[ +{ NAME => 'Jacob', ADDRESS => 'A place', PHONE => 'Some phone', }, +{ NAME => 'Matisse', ADDRESS => 'Another place', PHONE => 'A different phone', }, ] and for each entry in that list, it will use the hash ref as a miniature set of tags for that entry. If you want to use the long way to make a list (not recommended; it's what add_list_tag() uses internally), there are three things you need to set: A list (array). An entry template. A subroutine that takes one element of the list as an argument and returns a hash reference to a set of tags (which should appear in the entry_template.) You set the list of elements that you want to be made into a parsed list using the list() method. It just takes a list. Obviously, the ordering in that list is important. Each element is a scalar, but it can be a reference, of course, and will usually be either a key or a reference to a more complex set of data. For example: list( $jacob, $matisse, $alejandro ); or list( \%hash1, \%hash2, \%hash3 ); You set the templates for the entry and join templates with the entry_string() & join_string() or entry_file() & join_file() methods. These work in the way you would expect. For example: entry_string( '

    Name: <#NAME>

    City: <#CITY>

    ' ); join_string( '' ); or: entry_file( 'entry.htmlf' ); join_file( 'join.htmlf' ); Usually the _file methods are the ones you want. In the join template, you can either just use the existing tags stored in the object (which is recommended, since usually you don't care what's in the join template, if you use it at all) or you can supply your own set of tags with the join_tags() method, which works just like the tags() method. The complicated part is the callback. You must supply a subroutine to generate the tags for each entry. It's easier than it seems. The callback is set with the entry_callback() method. It is called for each entry in the list, and its sole argument will be the item we are looking at from the list, a single scalar. It must return a hash-ref of name/action pairs of the tags that appear in the entry template. A callback might look like this: entry_callback( sub { my( $person ) = @_; # $person is assumed to be a hash-ref my $tags= +{ NAME => $person->name, CITY => $person->city }; return $tags; } ); You then have to make the list from this stuff, using the parse_list() or parse_list_files() methods. These return the full parsed list as a string. For example: $list = parse_list; or more often you'll be wanting to put that into another tag to put into your full-page template, like: add_tag( LIST => parse_list_files ); That example above might produce a parsed list looking like:

    Name: Jacob

    City: Norwich

    Name: Matisse

    City: San Francisco

    Name: Alejandro

    City: San Francisco

    which you could then insert into your output. If you're lazy and each item in your list is either a hashref or can easily be turned into one (for example, by returning a row from a database as a hashref) you may just want to return it directly, like this: entry_callback( sub { ( $userid ) = @_; $sth = $dbh->prepare( <<"EOS" ); SELECT * FROM users WHERE userid = "$userid" EOS $sth->execute; return $sth->fetchrow_hashref; } ); or more even more lazily, something like this: $sth = $dbh->prepare( <<"EOS" ); SELECT * FROM users EOS $sth->execute; while ( $user = $sth->fetchrow_hashref ) { push @users, $user; } list( @users ); entry_callback( sub { return $_[ 0 ] } ); Isn't that easy? What's even easier is that the default value for entry_callback() is `sub { return $_[ 0 ] }', so if your list is a list of hashrefs, you don't even need to touch it. WHICH INTERFACE? ================ You have a choice when using this module. You may either use an object-oriented interface, where you create new instances of Text::TagTemplate objects and call methods on them, or you may use the conventional interface, where you import these methods into your namespace and call them without an object reference. This is very similar to the way the CGI module does things. I recommend the latter method, because the other forces you to do a lot of object referencing that isn't particularly clear to read. You might need to use it if you want multiple objects or you are concerned about namespace conflicts. You'll also want to use the object interface if you're running under mod_perl, because mod_perl uses a global to store the template object, and it won't get deallocated between handler calls. For the OO interface, just use: use Text::TagTemplate; my $parser = new Text::TagTemplate; For the conventional interface, use: use Text::TagTemplate qw( :standard ); and you'll get all the commonly-used methods automatically imported. If you want the more obscure configuration methods, you can have them too with: use Text::TagTemplate qw( :standard :config ); The examples given here all use the conventional interface, for clarity. The OO interface would look like: $parser = new Text::TagTemplate; $parser->template_file( 'default.htmlt' ); $parser->parse; PER-METHOD DOCUMENTATION ======================== new() or `new( %tags )' or `new( \%tags )' Instantiate a new template object. Optionally take a hash or hash-ref of tags to add initially. `auto_cap()' or `auto_cap( $new_value )' Returns whether tag names will automatically be capitalised, and if a value is supplied sets the auto-capitalisation to this value first. Default is 1; changing it is not recommended but hey go ahead and ignore me anyway, what do I know? Setting it to false will make tag names case-sensitive and you probably don't want that. `unknown_action()' or `unknown_action( $action )' Returns what to do with unknown tags. If a value is supplied sets the action to this value first. If the action is the special value 'DIE' then it will die at that point. This is the default. If the action is the special value 'IGNORE' then unknown tags will be ignored by the module, and will appear unchanged in the parsed output. If the special value 'WARN' is used then the the unknown tags will be replaced by warning text and logged with a warn() call. Other special values may be supplied later, so if scalar actions are require it is suggested that a scalar ref be supplied, where these special actions will not be taken no matter what the value. tags() or `tags( %tags )' or `tags( \%tags )' Returns the contents of the tags as a hash-ref of tag/action pairs. If tags are supplied as a hash or hashref, it first sets the contents to these tags, clearing all previous tags. `add_tag( $tag_name, $tag_action )' Adds a new tag. Takes a tag name and the tag action. `add_list_tag( $tag_name, \@list, $entry_callback, @join_tags )' Add a tag that will build a parsed list, allowing the person using the tag to supply the filename of the entry and join templates, or to supply the strings directly in tag parameters (which is currently annoying given the way they need to be escaped). The tag will take parameters for ENTRY_STRING, ENTRY_FILE, JOIN_STRING or JOIN_FILE. No checking is currently performed on the filenames given. This shouldn't be a security problem unless you're allowing untrusted users to write your templates for you, which mean it's a bug that I need to fix (since I want untrusted users to be able to write templates under some circumstnaces). `add_tags( %tags )' or `add_tags( \%tags )' Adds a bunch of tags. Takes a hash or hash-ref of tag/action pairs. `delete_tag( $name )' Delete a tag by name. `clear_tags()' Clears all existing tags. list() or `list( @list )' Returns (and sets if supplied) the list of values to be used in parse_list() or parse_list_files() calls. `template_string()' or `template_string( $string )' Returns (and sets if supplied) the default template string for parse(). `template_file()' or `template_file( $file )' Returns (and sets if supplied) the default template file for parse_file(). `entry_string()' or `entry_string( $string )' Returns (and sets if supplied) the entry string to be used in parse_list() calls. `entry_file()' or `entry_file( $file )' Returns (and sets if supplied) the entry file to be used in parse_list_files() calls. `entry_callback()' or `entry_callback( $callback )' Returns (and sets if supplied) the callback sub to be used in parse_list() or parse_list_files() calls. If you don't set this, the default is just to return the item passed in, which will only work if the item is a hashref suitable for use as a set of tags. `join_string()' or `join_string( $string )' Returns (and sets if supplied) the join string to be used in parse_list() calls. `join_file()' or `join_file( $file )' Returns (and sets if supplied) the join file to be used in parse_list_files() calls. `join_tags()' or `join_tags( %tags )' or `join_tags( \%tags )' Returns (and sets if supplied) the join tags to be used in parse_list() and parse_list_files() calls. parse() or `parse( $string )' or `parse( $string, %tags )' or `parse( $string, \%tags )' Parse a string, either the default string, or a string supplied. Returns the string. Can optionally also take the tags hash or hash-ref directly as well. parse_file() or `parse_file( $file )' or `parse_file( $file, %tags )' or `parse_file( $file, \%tags )' Parses a file, either the default file or the supplied filename. Returns the parsed file. Dies if the file cannot be read. Can optionally take the tags hash or hash-ref directly. `parse_list()' or `parse_list( \@list )' or `parse_list( \@list, $entry_string, $join_string )' or `parse_list( \@list, $entry_string, $join_string, $entry_callback, \%join_tags )' Makes a string from a list of entries, either the default or a supplied list. At least one template string is needed: the one to use for each entry, and another is optional, to be used to join the entries. A callback subroutine must be supplied using entry_callback(), which takes the entry value from the list and must return a hash-ref of tags to be interpolated in the entry string. This will be called for each entry in the list. You can also supply a set of tags for the join string using join_tags(), but by default the main tags will be used in that string. You can also optionally supply the strings for the entry and join template. Otherwise the strings set previously (with entry_string() and join_string() ) will be used. Finally, you can also supply the callback sub and join tags directly if you want. `parse_list_files()' or `parse_list_files( \@list )' or `parse_list_files( \@list, $entry_file, $join_file )' or `parse_list_files( \@list, $entry_file, $join_file, $entry_callback )' or `parse_list_files( \@list, $entry_file, $join_file, $entry_callback, %join_tags )' or `parse_list_files( \@list, $entry_file, $join_file, $entry_callback, \%join_tags )' Exactly as parse_list(), but using filenames, not strings. COPYRIGHT ========= Copyright (C) 2000 SF Interactive, Inc. All rights reserved. LICENSE ======= This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA AUTHOR ====== Jacob Davies SEE ALSO ======== The README file supplied with the distribution, and the example/ subdirectory there, which contains a full CGI application using this module. The CGI module documentation. Apache::TagRegistry(1)  File: pm.info, Node: Text/Template, Next: Text/Thesaurus/ISO, Prev: Text/TagTemplate, Up: Module List Expand template text with embedded Perl *************************************** NAME ==== Text::Template - Expand template text with embedded Perl VERSION ======= This file documents `Text::Template' version *1.30* SYNOPSIS ======== use Text::Template; $template = new Text::Template (TYPE => FILE, SOURCE => 'filename.tmpl'); $template = new Text::Template (TYPE => ARRAY, SOURCE => [ ... ] ); $template = new Text::Template (TYPE => FILEHANDLE, SOURCE => $fh ); $template = new Text::Template (TYPE => STRING, SOURCE => '...' ); $template = new Text::Template (PREPEND => q{use strict;}, ...); # Use a different template file syntax: $template = new Text::Template (DELIMITERS => [$open, $close], ...); $recipient = 'King'; $text = $template->fill_in(); # Replaces `{$recipient}' with `King' print $text; $T::recipient = 'Josh'; $text = $template->fill_in(PACKAGE => T); $hash = { recipient => 'Abed-Nego' }; $text = $template->fill_in(HASH => $hash, ...); # Recipient is Abed-Nego # Call &callback in case of programming errors in template $text = $template->fill_in(BROKEN => \&callback, BROKEN_ARG => [...]); # Evaluate program fragments in Safe compartment with restricted permissions $text = $template->fill_in(SAFE => $compartment, ...); # Print result text instead of returning it $success = $template->fill_in(OUTPUT => \*FILEHANDLE, ...); # Parse template with different template file syntax: $text = $template->fill_in(DELIMITERS => [$open, $close], ...); # Note that this is *faster* than using the default delimiters # Prepend specified perl code to each fragment before evaluating: $text = $template->fill_in(PREPEND => q{use strict 'vars';}, ...); use Text::Template 'fill_in_string'; $text = fill_in_string( < 'T', ...); Dear {$recipient}, Pay me at once. Love, G.V. EOM use Text::Template 'fill_in_file'; $text = fill_in_file($filename, ...); # All templates will always have `use strict vars' attached to all fragments Text::Template->always_prepend(q{use strict 'vars';}); DESCRIPTION =========== This is a library for generating form letters, building HTML pages, or filling in templates generally. A `template' is a piece of text that has little Perl programs embedded in it here and there. When you `fill in' a template, you evaluate the little programs and replace them with their values. You can store a template in a file outside your program. People can modify the template without modifying the program. You can separate the formatting details from the main code, and put the formatting parts of the program into the template. That prevents code bloat and encourages functional separation. Example ------- Here's an example of a template, which we'll suppose is stored in the file `formletter.tmpl': Dear {$title} {$lastname}, It has come to our attention that you are delinquent in your {$monthname[$last_paid_month]} payment. Please remit ${sprintf("%.2f", $amount)} immediately, or your patellae may be needlessly endangered. Love, Mark "Vizopteryx" Dominus The result of filling in this template is a string, which might look something like this: Dear Mr. Gates, It has come to our attention that you are delinquent in your February payment. Please remit $392.12 immediately, or your patellae may be needlessly endangered. Love, Mark "Vizopteryx" Dominus Here is a complete program that transforms the example template into the example result, and prints it out: use Text::Template; my $template = new Text::Template (SOURCE => 'formletter.tmpl') or die "Couldn't construct template: $Text::Template::ERROR"; my @monthname = qw(January February March April May June July August September October November December); my %vars = (title => 'Mr.', firstname => 'Bill', lastname => 'Gates', last_paid_month => 1, # February amount => 392.12, monthname => \@monthname, ); my $result = $template->fill_in(HASH => \%vars); if (defined $result) { print $result } else { die "Couldn't fill in template: $Text::Template::ERROR" } Philosophy ---------- When people make a template module like this one, they almost always start by inventing a special syntax for substitutions. For example, they build it so that a string like `%%VAR%%' is replaced with the value of `$VAR'. Then they realize the need extra formatting, so they put in some special syntax for formatting. Then they need a loop, so they invent a loop syntax. Pretty soon they have a new little template language. This approach has two problems: First, their little language is crippled. If you need to do something the author hasn't thought of, you lose. Second: Who wants to learn another language? You already know Perl, so why not use it? `Text::Template' templates are programmed in Perl. You embed Perl code in your template, with `{' at the beginning and `}' at the end. If you want a variable interpolated, you write it the way you would in Perl. If you need to make a loop, you can use any of the Perl loop constructions. All the Perl built-in functions are available. Details ======= Template Parsing ---------------- The `Text::Template' module scans the template source. An open brace `{' begins a program fragment, which continues until the matching close brace `}'. When the template is filled in, the program fragments are evaluated, and each one is replaced with the resulting value to yield the text that is returned. A backslash \ in front of a brace (or another backslash that is in front of a brace) escapes its special meaning. The result of filling out this template: \{ The sum of 1 and 2 is {1+2} \} is { The sum of 1 and 2 is 3 } If you have an unmatched brace, `Text::Template' will return a failure code and a warning about where the problem is. Backslashes that do not precede a brace are passed through unchanged. If you have a template like this: { "String that ends in a newline.\n" } The backslash inside the string is passed through to Perl unchanged, so the \n really does turn into a newline. See the note at the end for details about the way backslashes work. Backslash processing is not done when you specify alternative delimiters with the `DELIMITERS' option. (See `"Alternative Delimiters"' in this node, below.) Each program fragment should be a sequence of Perl statements, which are evaluated the usual way. The result of the last statement executed will be evaluted in scalar context; the result of this statement is a string, which is interpolated into the template in place of the program fragment itself. The fragments are evaluated in order, and side effects from earlier fragments will persist into later fragments: {$x = @things; ''}The Lord High Chamberlain has gotten {$x} things for me this year. { $diff = $x - 17; $more = 'more' if ($diff == 0) { $diff = 'no'; } elsif ($diff < 0) { $more = 'fewer'; } ''; } That is {$diff} {$more} than he gave me last year. The value of $x set in the first line will persist into the next fragment that begins on the third line, and the values of `$diff' and `$more' set in the second fragment will persist and be interpolated into the last line. The output will look something like this: The Lord High Chamberlain has gotten 42 things for me this year. That is 35 more than he gave me last year. That is all the syntax there is. The `$OUT' variable ------------------- There is one special trick you can play in a template. Here is the motivation for it: Suppose you are going to pass an array, `@items', into the template, and you want the template to generate a bulleted list with a header, like this: Here is a list of the things I have got for you since 1907: * Ivory * Apes * Peacocks * ... One way to do it is with a template like this: Here is a list of the things I have got for you since 1907: { my $blist = ''; foreach $i (@items) { $blist .= qq{ * $i\n}; } $blist; } Here we construct the list in a variable called `$blist', which we return at the end. This is a little cumbersome. There is a shortcut. Inside of templates, there is a special variable called `$OUT'. Anything you append to this variable will appear in the output of the template. Also, if you use `$OUT' in a program fragment, the normal behavior, of replacing the fragment with its return value, is disabled; instead the fragment is replaced with the value of `$OUT'. This means that you can write the template above like this: Here is a list of the things I have got for you since 1907: { foreach $i (@items) { $OUT .= " * $i\n"; } } `$OUT' is reinitialized to the empty string at the start of each program fragment. It is private to `Text::Template', so you can't use a variable named `$OUT' in your template without invoking the special behavior. General Remarks --------------- All `Text::Template' functions return undef on failure, and set the variable `$Text::Template::ERROR' to contain an explanation of what went wrong. For example, if you try to create a template from a file that does not exist, `$Text::Template::ERROR' will contain something like: Couldn't open file xyz.tmpl: No such file or directory new --- $template = new Text::Template ( TYPE => ..., SOURCE => ... ); This creates and returns a new template object. new returns undef and sets `$Text::Template::ERROR' if it can't create the template object. SOURCE says where the template source code will come from. TYPE says what kind of object the source is. The most common type of source is a file: new Text::Template ( TYPE => 'FILE', SOURCE => $filename ); This reads the template from the specified file. The filename is opened with the Perl open command, so it can be a pipe or anything else that makes sense with open. The TYPE can also be STRING, in which case the SOURCE should be a string: new Text::Template ( TYPE => 'STRING', SOURCE => "This is the actual template!" ); The TYPE can be ARRAY, in which case the source should be a reference to an array of strings. The concatenation of these strings is the template: new Text::Template ( TYPE => 'ARRAY', SOURCE => [ "This is ", "the actual", " template!", ] ); The TYPE can be FILEHANDLE, in which case the source should be an open filehandle (such as you got from the FileHandle or `IO::*' packages, or a glob, or a reference to a glob). In this case `Text::Template' will read the text from the filehandle up to end-of-file, and that text is the template: # Read template source code from STDIN: new Text::Template ( TYPE => 'FILEHANDLE', SOURCE => \*STDIN ); If you omit the TYPE attribute, it's taken to be FILE. SOURCE is required. If you omit it, the program will abort. The words TYPE and SOURCE can be spelled any of the following ways: TYPE SOURCE Type Source type source -TYPE -SOURCE -Type -Source -type -source Pick a style you like and stick with it. `DELIMITERS' You may also add a `DELIMITERS' option. If this option is present, its value should be a reference to an array of two strings. The first string is the string that signals the beginning of each program fragment, and the second string is the string that signals the end of each program fragment. See `"Alternative Delimiters"' in this node, below. compile ------- $template->compile() Loads all the template text from the template's source, parses and compiles it. If successful, returns true; otherwise returns false and sets `$Text::Template::ERROR'. If the template is already compiled, it returns true and does nothing. You don't usually need to invoke this function, because `fill_in' (see below) compiles the template if it isn't compiled already. If there is an argument to this function, it must be a reference to an array containing alternative delimiter strings. See `"Alternative Delimiters"', below. `fill_in' --------- $template->fill_in(OPTIONS); Fills in a template. Returns the resulting text if successful. Otherwise, returns undef and sets `$Text::Template::ERROR'. The OPTIONS are a hash, or a list of key-value pairs. You can write the key names in any of the six usual styles as above; this means that where this manual says PACKAGE (for example) you can actually use any of PACKAGE Package package -PACKAGE -Package -package Pick a style you like and stick with it. The all-lowercase versions may yield spurious warnings about Ambiguous use of package => resolved to "package" so you might like to avoid them and use the capitalized versions. At present, there are seven legal options: PACKAGE, `BROKEN', `BROKEN_ARG', SAFE, HASH, OUTPUT, and `DELIMITERS'. PACKAGE PACKAGE specifies the name of a package in which the program fragments should be evaluated. The default is to use the package from which `fill_in' was called. For example, consider this template: The value of the variable x is {$x}. If you use `$template->fill_in(PACKAGE => 'R')' , then the $x in the template is actually replaced with the value of `$R::x'. If you omit the PACKAGE option, $x will be replaced with the value of the $x variable in the package that actually called `fill_in'. You should almost always use PACKAGE. If you don't, and your template makes changes to variables, those changes will be propagated back into the main program. Evaluating the template in a private package helps prevent this. The template can still modify variables in your program if it wants to, but it will have to do so explicitly. See the section at the end on `Security'. Here's an example of using PACKAGE: Your Royal Highness, Enclosed please find a list of things I have gotten for you since 1907: { foreach $item (@items) { $item_no++; $OUT .= " $item_no. \u$item\n"; } } Signed, Lord High Chamberlain We want to pass in an array which will be assigned to the array `@items'. Here's how to do that: @items = ('ivory', 'apes', 'peacocks', ); $template->fill_in(); This is not very safe. The reason this isn't as safe is that if you had a variable named `$item_no' in scope in your program at the point you called `fill_in', its value would be clobbered by the act of filling out the template. The problem is the same as if you had written a subroutine that used those variables in the same way that the template does. (`$OUT' is special in templates and is always safe.) One solution to this is to make the `$item_no' variable private to the template by declaring it with my. If the template does this, you are safe. But if you use the PACKAGE option, you will probably be safe even if the template does not declare its variables with my: @Q::items = ('ivory', 'apes', 'peacocks', ); $template->fill_in(PACKAGE => 'Q'); In this case the template will clobber the variable `$Q::item_no', which is not related to the one your program was using. Templates cannot affect variables in the main program that are declared with my, unless you give the template references to those variables. HASH You may not want to put the template variables into a package. Packages can be hard to manage: You can't copy them, for example. HASH provides an alternative. The value for HASH should be a reference to a hash that maps variable names to values. For example, $template->fill_in(HASH => { recipient => "The King", items => ['gold', 'frankincense', 'myrrh'] }); will fill out the template and use `"The King"' as the value of `$recipient' and the list of items as the value of `@items'. The full details of how it works are a little involved, so you might want to skip to the next section. Suppose the key in the hash is key and the value is value. * If the value is undef, then any variables named $key, `@key', `%key', etc., are undefined. * If the value is a string or a number, then $key is set to that value in the template. * If the value is a reference to an array, then `@key' is set to that array. If the value is a reference to a hash, then `%key' is set to that hash. Similarly if value is any other kind of reference. This means that var => "foo" and var => \"foo" have almost exactly the same effect. (The difference is that in the former case, the value is copied, and in the latter case it is aliased.) Normally, the way this works is by allocating a private package, loading all the variables into the package, and then filling out the template as if you had specified that package. A new package is allocated each time. However, if you *also* use the PACKAGE option, `Text::Template' loads the variables into the package you specified, and they stay there after the call returns. Subsequent calls to `fill_in' that use the same package will pick up the values you loaded in. If the argument of HASH is a reference to an array instead of a reference to a hash, then the array should contain a list of hashes whose contents are loaded into the template package one after the other. You can use this feature if you want to combine several sets of variables. For example, one set of variables might be the defaults for a fill-in form, and the second set might be the user inputs, which override the defaults when they are present: $template->fill_in(HASH => [\%defaults, \%user_input]); You can also use this to set two variables with the same name: $template->fill_in(HASH => [{ v => "The King" }, { v => [1,2,3] }, ] ); This sets `$v' to `"The King"' and `@v' to `(1,2,3)'. `BROKEN' If any of the program fragments fails to compile or aborts for any reason, and you have set the `BROKEN' option to a function reference, `Text::Template' will invoke the function. This function is called the *`BROKEN' function*. The `BROKEN' function will tell `Text::Template' what to do next. If the `BROKEN' function returns undef, `Text::Template' will immediately abort processing the template and return the text that it has accumulated so far. If your function does this, it should set a flag that you can examine after `fill_in' returns so that you can tell whether there was a premature return or not. If the `BROKEN' function returns any other value, that value will be interpolated into the template as if that value had been the return value of the program fragment to begin with. For example, if the `BROKEN' function returns an error string, the error string will be interpolated into the output of the template in place of the program fragment that cased the error. If you don't specify a `BROKEN' function, `Text::Template' supplies a default one that returns something like Program fragment at line 17 delivered error ``Illegal division by 0'' Since this is interpolated into the template at the place the error occurred, a template like this one: (3+4)*5 = { 3+4)*5 } yields this result: (3+4)*5 = Program fragment at line 1 delivered error ``syntax error'' If you specify a value for the `BROKEN' attribute, it should be a reference to a function that `fill_in' can call instead of the default function. `fill_in' will pass a hash to the `broken' function. The hash will have at least these three members: text The source code of the program fragment that failed error The text of the error message (`$@') generated by eval lineno The line number of the template data at which the program fragment began There may also be an `arg' member. See `BROKEN_ARG', below `BROKEN_ARG' If you supply the `BROKEN_ARG' option to `fill_in', the value of the option is passed to the `BROKEN' function whenever it is called. The default `BROKEN' function ignores the `BROKEN_ARG', but you can write a custom `BROKEN' function that uses the `BROKEN_ARG' to get more information about what went wrong. The `BROKEN' function could also use the `BROKEN_ARG' as a reference to store an error message or some other information that it wants to communicate back to the caller. For example: $error = ''; sub my_broken { my %args = @_; my $err_ref = $args{arg}; ... $$err_ref = "Some error message"; return undef; } $template->fill_in(BROKEN => \&my_broken, BROKEN_ARG => \$error, ); if ($error) { die "It didn't work: $error"; } If one of the program fragments in the template fails, it will call the `BROKEN' function, `my_broken', and pass it the `BROKEN_ARG', which is a reference to $error. `my_broken' can store an error message into $error this way. Then the function that called `fill_in' can see if `my_broken' has left an error message for it to find, and proceed accordingly. SAFE If you give `fill_in' a SAFE option, its value should be a safe compartment object from the Safe package. All evaluation of program fragments will be performed in this compartment. See *Note Safe: Safe, for full details about such compartments and how to restrict the operations that can be performed in them. If you use the PACKAGE option with SAFE, the package you specify will be placed into the safe compartment and evaluation will take place in that package as usual. If not, SAFE operation is a little different from the default. Usually, if you don't specify a package, evaluation of program fragments occurs in the package from which the template was invoked. But in SAFE mode the evaluation occurs inside the safe compartment and cannot affect the calling package. Normally, if you use HASH without PACKAGE, the hash variables are imported into a private, one-use-only package. But if you use HASH and SAFE together without PACKAGE, the hash variables will just be loaded into the root namespace of the Safe compartment. OUTPUT If your template is going to generate a lot of text that you are just going to print out again anyway, you can save memory by having `Text::Template' print out the text as it is generated instead of making it into a big string and returning the string. If you supply the OUTPUT option to `fill_in', the value should be a filehandle. The generated text will be printed to this filehandle as it is constructed. For example: $template->fill_in(OUTPUT => \*STDOUT, ...); fills in the $template as usual, but the results are immediately printed to STDOUT. This may result in the output appearing more quickly than it would have otherwise. If you use OUTPUT, the return value from `fill_in' is still true on success and false on failure, but the complete text is not returned to the caller. `PREPEND' You can have some Perl code prepended automatically to the beginning of every program fragment. See ``PREPEND' in this node feature and using `strict' in templates' below. `DELIMITERS' If this option is present, its value should be a reference to a list of two strings. The first string is the string that signals the beginning of each program fragment, and the second string is the string that signals the end of each program fragment. See `"Alternative Delimiters"' in this node, below. If you specify `DELIMITERS' in the call to `fill_in', they override any delimiters you set when you created the template object with new. Convenience Functions ===================== `fill_this_in' -------------- The basic way to fill in a template is to create a template object and then call `fill_in' on it. This is useful if you want to fill in the same template more than once. In some programs, this can be cumbersome. `fill_this_in' accepts a string, which contains the template, and a list of options, which are passed to `fill_in' as above. It constructs the template object for you, fills it in as specified, and returns the results. It returns undef and sets `$Text::Template::ERROR' if it couldn't generate any results. An example: $Q::name = 'Donald'; $Q::amount = 141.61; $Q::part = 'hyoid bone'; $text = Text::Template->fill_this_in( <<'EOM', PACKAGE => Q); Dear {$name}, You owe me \\${sprintf('%.2f', $amount)}. Pay or I will break your {$part}. Love, Grand Vizopteryx of Irkutsk. EOM Notice how we included the template in-line in the program by using a `here document' with the `<<' notation. `fill_this_in' is a deprecated feature. It is only here for backwards compatibility, and may be removed in some far-future version in `Text::Template'. You should use `fill_in_string' instead. It is described in the next section. `fill_in_string' ---------------- It is stupid that `fill_this_in' is a class method. It should have been just an imported function, so that you could omit the `Text::Template->' in the example above. But I made the mistake four years ago and it is too late to change it. `fill_in_string' is exactly like `fill_this_in' except that it is not a method and you can omit the `Text::Template->' and just say print fill_in_string(<<'EOM', ...); Dear {$name}, ... EOM To use `fill_in_string', you need to say use Text::Template 'fill_in_string'; at the top of your program. You should probably use `fill_in_string' instead of `fill_this_in'. `fill_in_file' -------------- If you import `fill_in_file', you can say $text = fill_in_file(filename, ...); The ... are passed to `fill_in' as above. The filename is the name of the file that contains the template you want to fill in. It returns the result text. or undef, as usual. If you are going to fill in the same file more than once in the same program you should use the longer new / `fill_in' sequence instead. It will be a lot faster because it only has to read and parse the file once. Including files into templates ------------------------------ People always ask for this. "Why don't you have an include function?" they want to know. The short answer is this is Perl, and Perl already has an include function. If you want it, you can just put {qx{cat filename}} into your template. VoilE. If you don't want to use cat, you can write a little four-line function that opens a file and dumps out its contents, and call it from the template. I wrote one for you. In the template, you can say {Text::Template::_load_text(filename)} If that is too verbose, here is a trick. Suppose the template package that you are going to be mentioning in the `fill_in' call is package Q. Then in the main program, write *Q::include = \&Text::Template::_load_text; This imports the `_load_text' function into package Q with the name include. From then on, any template that you fill in with package Q can say {include(filename)} to insert the text from the named file at that point. If you are using the HASH option instead, just put `include => \&Text::Template::_load_text' into the hash instead of importing it explicitly. Suppose you don't want to insert a plain text file, but rather you want to include one template within another? Just use `fill_in_file' in the template itself: {Text::Template::fill_in_file(filename)} You can do the same importing trick if this is too much to type. Miscellaneous ============= my variables ------------ People are frequently surprised when this doesn't work: my $recipient = 'The King'; my $text = fill_in_file('formletter.tmpl'); The text `The King' doesn't get into the form letter. Why not? Because `$recipient' is a my variable, and the whole point of my variables is that they're private and inaccessible except in the scope in which they're declared. The template is not part of that scope, so the template can't see `$recipient'. If that's not the behavior you want, don't use my. my means a private variable, and in this case you don't want the variable to be private. Put the variables into package variables in some other package, and use the PACKAGE option to `fill_in': $Q::recipient = $recipient; my $text = fill_in_file('formletter.tmpl', PACKAGE => 'Q'); or pass the names and values in a hash with the HASH option: my $text = fill_in_file('formletter.tmpl', HASH => { recipient => $recipient }); Security Matters ---------------- All variables are evaluated in the package you specify with the PACKAGE option of `fill_in'. if you use this option, and if your templates don't do anything egregiously stupid, you won't have to worry that evaluation of the little programs will creep out into the rest of your program and wreck something. Nevertheless, there's really no way (except with Safe) to protect against a template that says { $Important::Secret::Security::Enable = 0; # Disable security checks in this program } or { $/ = "ho ho ho"; # Sabotage future uses of . # $/ is always a global variable } or even { system("rm -rf /") } so *don't* go filling in templates unless you're sure you know what's in them. If you're worried, or you can't trust the person who wrote the template, use the SAFE option. A final warning: program fragments run a small risk of accidentally clobbering local variables in the `fill_in' function itself. These variables all have names that begin with `$fi_', so if you stay away from those names you'll be safe. (Of course, if you're a real wizard you can tamper with them deliberately for exciting effects; this is actually how `$OUT' works.) I can fix this, but it will make the package slower to do it, so I would prefer not to. If you are worried about this, send me mail and I will show you what to do about it. Alternative Delimiters ---------------------- Lorenzo Valdettaro pointed out that if you are using `Text::Template' to generate TeX output, the choice of braces as the program fragment delimiters makes you suffer suffer suffer. Starting in version 1.20, you can change the choice of delimiters to something other than curly braces. In either the new() call or the `fill_in()' call, you can specify an alternative set of delimiters with the `DELIMITERS' option. For example, if you would like code fragments to be delimited by `[@--' and `--@]' instead of `{' and `}', use ... DELIMITERS => [ '[@--', '--@]' ], ... Note that these delimiters are *literal strings*, not regexes. (I tried for regexes, but it complicates the lexical analysis too much.) Note also that `DELIMITERS' disables the special meaning of the backslash, so if you want to include the delimiters in the literal text of your template file, you are out of luck--it is up to you to choose delimiters that do not conflict with what you are doing. The delimiter strings may still appear inside of program fragments as long as they nest properly. This means that if for some reason you absolutely must have a program fragment that mentions one of the delimiters, like this: [@-- print "Oh no, a delimiter: --@]\n" --@] you may be able to make it work by doing this instead: [@-- # Fake matching delimiter in a comment: [@-- print "Oh no, a delimiter: --@]\n" --@] It may be safer to choose delimiters that begin with a newline character. Because the parsing of templates is simplified by the absence of backslash escapes, using alternative `DELIMITERS' *speeds up* the parsing process by 20-25%. This shows that my original choice of `{' and `}' was very bad. I therefore recommend that you use alternative delimiters whenever possible. `PREPEND' feature and using strict in templates ----------------------------------------------- Suppose you would like to use strict in your templates to detect undeclared variables and the like. But each code fragment is a separate lexical scope, so you have to turn on strict at the top of each and every code fragment: { use strict; use vars '$foo'; $foo = 14; ... } ... { # we forgot to put `use strict' here my $result = $boo + 12; # $boo is misspelled and should be $foo # No error is raised on `$boo' } Because we didn't put `use strict' at the top of the second fragment, it was only active in the first fragment, and we didn't get any strict checking in the second fragment. Then we mispelled `$foo' and the error wasn't caught. `Text::Template' version 1.22 and higher has a new feature to make this easier. You can specify that any text at all be automatically added to the beginning of each program fragment. When you make a call to `fill_in', you can specify a PREPEND => 'some perl statements here' option; the statements will be prepended to each program fragment for that one call only. Suppose that the `fill_in' call included a PREPEND => 'use strict;' option, and that the template looked like this: { use vars '$foo'; $foo = 14; ... } ... { my $result = $boo + 12; # $boo is misspelled and should be $foo ... } The code in the second fragment would fail, because `$boo' has not been declared. `use strict' was implied, even though you did not write it explicitly, because the `PREPEND' option added it for you automatically. There are two other ways to do this. At the time you create the template object with new, you can also supply a `PREPEND' option, in which case the statements will be prepended each time you fill in that template. If the `fill_in' call has its own `PREPEND' option, this overrides the one specified at the time you created the template. Finally, you can make the class method call Text::Template->always_prepend('perl statements'); If you do this, then call calls to `fill_in' for any template will attach the perl statements to the beginning of each program fragment, except where overridden by `PREPEND' options to new or `fill_in'. Prepending in Derived Classes ----------------------------- This section is technical, and you should skip it on the first few readings. Normally there are three places that prepended text could come from. It could come from the `PREPEND' option in the `fill_in' call, from the `PREPEND' option in the new call that created the template object, or from the argument of the `always_prepend' call. `Text::Template' looks for these three things in order and takes the first one that it finds. In a subclass of `Text::Template', this last possibility is ambiguous. Suppose S is a subclass of `Text::Template'. Should Text::Template->always_prepend(...); affect objects in class Derived? The answer is that you can have it either way. The `always_prepend' value for `Text::Template' is normally stored in a hash variable named `%GLOBAL_PREPEND' under the key `Text::Template'. When `Text::Template' looks to see what text to prepend, it first looks in the template object itself, and if not, it looks in `$GLOBAL_PREPEND{*class*}' where class is the class to which the template object belongs. If it doesn't find any value, it looks in `$GLOBAL_PREPEND{'Text::Template'}'. This means that objects in class Derived *will* be affected by Text::Template->always_prepend(...); *unless* there is also a call to Derived->always_prepend(...); So when you're designing your derived class, you can arrange to have your objects ignore `Text::Template::always_prepend' calls by simply putting `Derived->always_prepend('')' at the top of your module. Of course, there is also a final escape hatch: Templates support a `prepend_text' that is used to look up the appropriate text to be prepended at `fill_in' time. Your derived class can override this method to get an arbitrary effect. JavaScript ---------- Jennifer D. St Clair asks: > Most of my pages contain JavaScript and Stylesheets. > How do I change the template identifier? Jennifer is worried about the braces in the JavaScript being taken as the delimiters of the Perl program fragments. Of course, disaster will ensue when perl tries to evaluate these as if they were Perl programs. The best choice is to find some unambiguous delimiter strings that you can use in your template instead of curly braces, and then use the `DELIMITERS' option. However, if you can't do this for some reason, there are two easy workarounds: 1. You can put \ in front of `{', `}', or \ to remove its special meaning. So, for example, instead of if (br== "n3") { // etc. } you can put if (br== "n3") \{ // etc. \} and it'll come out of the template engine the way you want. But here is another method that is probably better. To see how it works, first consider what happens if you put this into a template: { 'foo' } Since it's in braces, it gets evaluated, and obviously, this is going to turn into foo So now here's the trick: In Perl, `q{...}' is the same as `'...''. So if we wrote {q{foo}} it would turn into foo So for your JavaScript, just write {q{if (br== "n3") { // etc. }} } and it'll come out as if (br== "n3") { // etc. } which is what you want. Shut Up! -------- People sometimes try to put an initialization section at the top of their templates, like this: { ... $var = 17; } Then they complain because there is a 17 at the top of the output that they didn't want to have there. Remember that a program fragment is replaced with its own return value, and that in Perl the return value of a code block is the value of the last expression that was evaluated, which in this case is 17. If it didn't do that, you wouldn't be able to write `{$recipient}' and have the recipient filled in. To prevent the 17 from appearing in the output is very simple: { ... $var = 17; ''; } Now the last expression evaluated yields the empty string, which is invisible. If you don't like the way this looks, use { ... $var = 17; ($SILENTLY); } instead. Presumably, `$SILENTLY' has no value, so nothing will be interpolated. This is what is known as a `trick'. Compatibility ------------- Every effort has been made to make this module compatible with older versions. There are three exceptions. One is the output format of the default `BROKEN' subroutine; I decided that the old format was too verbose. If this bothers you, it's easy to supply a custom subroutine that yields the old behavior. The second is that the `$OUT' feature arrogates the `$OUT' variable for itself. If you had templates that happened to use a variable named `$OUT', you will have to change them to use some other variable or all sorts of strangeness may result. The third incompatibility is with the behavior of the \ metacharacter. In 0.1b, \\ was special everywhere, and the template processor always replaced it with a single backslash before passing the code to Perl for evaluation. The rule now is more complicated but probably more convenient. See the section on backslash processing, below, for a full discussion. With a minor change to fix the format of the default `BROKEN' subroutine, this version passes the test suite from the old version. (It is in `t/01-basic.t'.) The old test suite was too small, but it's a little reassuring. Backslash Processing -------------------- In `Text::Template' beta versions, the backslash was special whenever it appeared before a brace or another backslash. That meant that while `{"\n"}' did indeed generate a newline, `{"\\"}' did not generate a backslash, because the code passed to Perl for evaluation was `"\"' which is a syntax error. If you wanted a backslash, you would have had to write `{"\\\\"}'. In `Text::Template' versions 1.0 through 1.10, there was a bug: Backslash was special everywhere. In these versions, `{"\n"}' generated the letter n. The bug has been corrected in version 1.11, but I did not go back to exactly the old rule, because I did not like the idea of having to write `{"\\\\"}' to get one backslash. The rule is now more complicated to remember, but probably easier to use. The rule is now: Backslashes are always passed to Perl unchanged *unless* they occur as part of a sequence like `\\\\\\{' or `\\\\\\}'. In these contexts, they are special; \\ is replaced with \, and `\{' and `\}' signal a literal brace. Examples: \{ foo \} is not evaluated, because the \ before the braces signals that they should be taken literally. The result in the output looks like this: { foo } This is a syntax error: { "foo}" } because `Text::Template' thinks that the code ends at the first `}', and then gets upset when it sees the second one. To make this work correctly, use { "foo\}" } This passes `"foo}"' to Perl for evaluation. Note there's no \ in the evaluated code. If you really want a \ in the evaluated code, use { "foo\\\}" } This passes `"foo\}"' to Perl for evaluation. Starting with `Text::Template' version 1.20, backslash processing is disabled if you use the `DELIMITERS' option to specify alternative delimiter strings. A short note about `$Text::Template::ERROR' ------------------------------------------- In the past some people have fretted about `violating the package boundary' by examining a variable inside the `Text::Template' package. Don't feel this way. `$Text::Template::ERROR' is part of the published, official interface to this package. It is perfectly OK to inspect this variable. The interface is not going to change. If it really, really bothers you, you can import a function called `TTerror' that returns the current value of the `$ERROR' variable. So you can say: use Text::Template 'TTerror'; my $template = new Text::Template (SOURCE => $filename); unless ($template) { my $err = TTerror; die "Couldn't make template: $err; aborting"; } I don't see what benefit this has over just doing this: use Text::Template; my $template = new Text::Template (SOURCE => $filename) or die "Couldn't make template: $Text::Template::ERROR; aborting"; But if it makes you happy to do it that way, go ahead. Sticky Widgets in Template Files -------------------------------- The CGI module provides functions for `sticky widgets', which are form input controls that retain their values from one page to the next. Sometimes people want to know how to include these widgets into their template output. It's totally straightforward. Just call the CGI functions from inside the template: { $q->checkbox_group(NAME => 'toppings', LINEBREAK => true, COLUMNS => 3, VALUES => \@toppings, ); } Author ------ Mark-Jason Dominus, Plover Systems Please send questions and other remarks about this software to `mjd-perl-template@pobox.com' You can join a very low-volume (<10 messages per year) mailing list for announcements about this package. Send an empty note to `mjd-perl-template-request@plover.com' to join. For updates, visit `http://www.plover.com/~mjd/perl/Template/'. Support? -------- This software is version 1.0. It is a complete rewrite of an older package, and may have bugs. Suggestions and bug reports are always welcome. Send them to `mjd-perl-template@plover.com'. (That is my address, not the address of the mailing list. The mailing list address is a secret.) Thanks ------ Many thanks to the following people for offering support, encouragement, advice, and all the other good stuff. Klaus Arnhold / Kevin Atteson / Chris.Brezil / Mike Brodhead / Tom Brown / Tim Bunce / Juan E. Camacho / Joseph Cheek / San Deng / Bob Dougherty / Dan Franklin / Todd A. Green / Donald L. Greer Jr. / Michelangelo Grigni / Tom Henry / Matt X. Hunter / Robert M. Ioffe / Daniel LaLiberte / Reuven M. Lerner / Joel Meulenberg / Jason Moore / Bek Oberin / Ron Pero / Hans Persson / Jonathan Roy / Shabbir J. Safdar / Jennifer D. St Clair / Uwe Schneider / Randal L. Schwartz / Michael G Schwern / Brian C. Shensky / Niklas Skoglund / Tom Snee / Hans Stoop / Michael J. Suzio / Dennis Taylor / James H. Thompson / Shad Todd / Lorenzo Valdettaro / Larry Virden / Andy Wardley / Matt Womer / Andrew G Wood / Michaely Yeung Special thanks to: Jonathan Roy for telling me how to do the Safe support (I spent two years worrying about it, and then Jonathan pointed out that it was trivial.) Ranjit Bhatnagar for demanding less verbose fragments like they have in ASP, for helping me figure out the Right Thing, and, especially, for talking me out of adding any new syntax. These discussions resulted in the `$OUT' feature. Bugs and Caveats ---------------- my variables in `fill_in' are still susceptible to being clobbered by template evaluation. They all begin with `fi_', so avoid those names in your templates. The line number information will be wrong if the template's lines are not terminated by `"\n"'. You should let me know if this is a problem. If you do, I will fix it. The default format for reporting of broken program fragments has changed since version 0.1. The `$OUT' variable has a special meaning in templates, so you cannot use it as if it were a regular variable. There are not quite enough tests in the test suite.