1FastTemplate(3)       User Contributed Perl Documentation      FastTemplate(3)
2
3
4

NAME

6       CGI::FastTemplate - Perl extension for managing templates, and perform‐
7       ing variable interpolation.
8

SYNOPSIS

10         use CGI::FastTemplate;
11
12         $tpl = new CGI::FastTemplate();
13         $tpl = new CGI::FastTemplate("/path/to/templates");
14
15         CGI::FastTemplate->set_root("/path/to/templates");    ## all instances will use this path
16         $tpl->set_root("/path/to/templates");                 ## this instance will use this path
17
18         $tpl->define( main    => "main.tpl",
19                       row     => "table_row.tpl",
20                       all     => "table_all.tpl",
21                       );
22
23         $tpl->assign(TITLE => "I am the title.");
24
25         my %defaults = (  FONT   => "<font size=+2 face=helvetica>",
26                           EMAIL   => 'jmoore@sober.com',
27                           );
28         $tpl->assign(\%defaults);
29
30         $tpl->parse(ROWS      => ".row");      ## the '.' appends to ROWS
31         $tpl->parse(CONTENT   => ["row", "all"]);
32         $tpl->parse(CONTENT   => "main");
33
34         $tpl->print();            ## defaults to last parsed
35         $tpl->print("CONTENT");   ## same as print() as "CONTENT" was last parsed
36
37         $ref = $tpl->fetch("CONTENT");
38

DESCRIPTION

40       What is a template?
41
42       A template is a text file with variables in it.  When a template is
43       parsed, the variables are interpolated to text.  (The text can be a few
44       bytes or a few hundred kilobytes.)  Here is a simple template with one
45       variable ('$NAME'):
46
47         Hello $NAME.  How are you?
48
49       When are templates useful?
50
51       Templates are very useful for CGI programming, because adding HTML to
52       your perl code clutters your code and forces you to do any HTML modifi‐
53       cations.  By putting all of your HTML in separate template files, you
54       can let a graphic or interface designer change the look of your appli‐
55       cation without having to bug you, or let them muck around in your perl
56       code.
57
58       There are other templating modules on CPAN, what makes FastTemplate
59       different?
60
61       CGI::FastTemplate has the following attributes:
62
63       Speed
64
65       FastTemplate doesn't use eval, and parses with a single regular expres‐
66       sion.  It just does simple variable interpolation (i.e. there is no
67       logic that you can add to templates - you keep the logic in the code).
68       That's why it's has 'Fast' in it's name!
69
70       Efficiency
71
72       FastTemplate functions accept and return references whenever possible,
73       which saves needless copying of arguments (hashes, scalars, etc).
74
75       Flexibility
76
77       The API is robust and flexible, and allows you to build very complex
78       HTML documents or HTML interfaces.  It is 100% perl and works on Unix
79       or NT.  Also, it isn't restricted to building HTML documents -- it
80       could be used to build any ascii based document (e.g. postscript, XML,
81       email).
82
83       The similar modules on CPAN are:
84
85         Module          HTML::Template  (S/SA/SAMTREGAR/HTML-Template-0.04.tar.gz)
86         Module          Taco::Template  (KWILLIAMS/Taco-0.04.tar.gz)
87         Module          Text::BasicTemplate (D/DC/DCARRAWAY/Text-BasicTemplate-0.9.8.tar.gz)
88         Module          Text::Template  (MJD/Text-Template-1.20.tar.gz)
89         Module          HTML::Mason     (J/JS/JSWARTZ/HTML-Mason-0.5.1.tar.gz)
90
91       What are the steps to use FastTemplate?
92
93       The main steps are:
94
95           1. define
96           2. assign
97           3. parse
98           4. print
99
100       These are outlined in detail in CORE METHODS below.
101

CORE METHODS

103       define(HASH)
104
105       The method define() maps a template filename to a (usually shorter)
106       name. e.g.
107
108           my $tpl = new FastTemplate();
109           $tpl->define(   main   => "main.tpl",
110                           footer   => "footer.tpl",
111                           );
112
113       This new name is the name that you will use to refer to the templates.
114       Filenames should not appear in any place other than a define().
115
116       (Note: This is a required step!  This may seem like an annoying extra
117       step when you are dealing with a trivial example like the one above,
118       but when you are dealing with dozens of templates, it is very handy to
119       refer to templates with names that are indepandant of filenames.)
120
121       TIP: Since define() does not actually load the templates, it is faster
122       and more legible to define all the templates with one call to define().
123
124       define_nofile(HASH)   alias: define_raw(HASH)
125
126       Sometimes it is desireable to not have to create a separate template
127       file for each template (though in the long run it is usually better to
128       do so).  The method define_nofile() allows you to do this.  For exam‐
129       ple, if you were writing a news tool where you wanted to bold an item
130       if it was "new" you could do something like the following:
131
132           my $tpl = new FastTemplate();
133
134           $tpl->define_nofile(    new   => '<b>$ITEM_NAME</b> <BR>',
135                                   old   => '$ITEM_NAME <BR>');
136
137           if ($new)
138           {
139               $tpl->parse($ITEM   => "new");
140           }
141           else
142           {
143               $tpl->parse($ITEM   => "old");
144           }
145
146       Of course, now you, the programmer has to update how new items are dis‐
147       played, whereas if it was in a template, you could offload that task to
148       someone else.
149
150       define_nofile(HASH REF)   alias: define_raw(HASH REF)
151
152       A more efficient way of passing your arguments than using a real hash.
153       Just pass in a hash reference instead of a real hash.
154
155       assign(HASH)
156
157       The method assign() assigns values for variables.  In order for a vari‐
158       able in a template to be interpolated it must be assigned.  There are
159       two forms which have some important differences.  The simple form, is
160       to accept a hash and copy all the key/value pairs into a hash in Fast‐
161       Template.  There is only one hash in FastTemplate, so assigning a value
162       for the same key will overwrite that key.
163
164           e.g.
165
166           $tpl->assign(TITLE   => "king kong");
167           $tpl->assign(TITLE   => "godzilla");    ## overwrites "king kong"
168
169       assign(HASH REF)
170
171       A much more efficient way to pass in values is to pass in a hash refer‐
172       ence.  (This is particularly nice if you get back a hash or hash refer‐
173       ence from a database query.)  Passing a hash reference doesn't copy the
174       data, but simply keeps the reference in an array.  During parsing if
175       the value for a variable cannot be found in the main FastTemplate hash,
176       it starts to look through the array of hash references for the value.
177       As soon as it finds the value it stops.  It is important to remember to
178       remove hash references when they are no longer needed.
179
180           e.g.
181
182           my %foo = ("TITLE" => "king kong");
183           my %bar = ("TITLE" => "godzilla");
184
185           $tpl->assign(\%foo);   ## TITLE resolves to "king kong"
186           $tpl->clear_href(1);   ## remove last hash ref assignment (\%foo)
187           $tpl->assign(\%bar);   ## TITLE resolves to "godzilla"
188
189           $tpl->clear_href();    ## remove all hash ref assignments
190
191           $tpl->assign(\%foo);   ## TITLE resolves to "king kong"
192           $tpl->assign(\%bar);   ## TITLE _still_ resolves to "king kong"
193
194       parse(HASH)
195
196       The parse function is the main function in FastTemplate.  It accepts a
197       hash, where the keys are the TARGET and the values are the SOURCE tem‐
198       plates.  There are three forms the hash can be in:
199
200           $tpl->parse(MAIN => "main");                ## regular
201
202           $tpl->parse(MAIN => ["table", "main"]);     ## compound
203
204           $tpl->parse(MAIN => ".row");                ## append
205
206       In the regular version, the template named "main" is loaded if it
207       hasn't been already, all the variables are interpolated, and the result
208       is then stored in FastTemplate as the value MAIN.  If the variable
209       '$MAIN' shows up in a later template, it will be interpolated to be the
210       value of the parsed "main" template.  This allows you to easily nest
211       templates, which brings us to the compound style.
212
213       The compound style is designed to make it easier to nest templates.
214       The following are equivalent:
215
216           $tpl->parse(MAIN => "table");
217           $tpl->parse(MAIN => "main");
218
219           ## is the same as:
220
221           $tpl->parse(MAIN => ["table", "main"]);     ## this form saves function calls
222                                                       ## (and makes your code cleaner)
223
224       It is important to note that when you are using the compound form, each
225       template after the first, must contain the variable that you are pars‐
226       ing the results into.  In the above example, 'main' must contain the
227       variable '$MAIN', as that is where the parsed results of 'table' is
228       stored.  If 'main' does not contain the variable '$MAIN' then the
229       parsed results of 'table' will be lost.
230
231       The append style is a bit of a kludge, but it allows you to append the
232       parsed results to the target variable.  This is most useful when build‐
233       ing tables that have an dynamic number of rows - such as data from a
234       database query.
235
236       strict()
237
238       When strict() is on (it is on by default) all variables found during
239       template parsing that are unresolved have a warning printed to STDERR.
240       e.g.
241
242          [CGI::FastTemplate] Warning: no value found for variable: SOME_VARIABLE
243
244       Also, new as of version 1.04 the variables will be left in the output
245       document.  This was done for two reasons: to allow for parsing to be
246       done in stages (i.e. multiple passes), and to make it easier to iden‐
247       tify undefined variables since they appear in the parsed output.  If
248       you have been using an earlier version of FastTemplate and you want the
249       old behavior of replacing unknown variables with an empty string, see:
250       no_strict().
251
252       Note: version 1.07 adds support for two styles of variables, so that
253       the following are equivalent: $VAR and ${VAR} However, when using
254       strict(), variables with curly brackets that are not resolved are out‐
255       putted as plain variables.  e.g. if ${VAR} has no value assigned to it,
256       it would appear in the output as $VAR.  This is a slight inconsistency
257       -- ideally the unresolved variable would remain unchanged.
258
259       Note: STDERR output should be captured and logged by the webserver so
260       you can just tail the error log to see the output.
261
262           e.g.
263
264           tail -f /etc/httpd/logs/error_log
265
266       no_strict()
267
268       Turns off warning messages about unresolved template variables.  As of
269       version 1.04 a call to no_strict() is required to replace unknown vari‐
270       ables with an empty string.  By default, all instances of FastTemplate
271       behave as is strict() was called.  Also, no_strict() must be set for
272       each instance of CGI::FastTemplate. e.g.
273
274          CGI::FastTemplate::no_strict;        ## no
275
276          my $tpl = CGI::FastTemplate;
277          $tpl->no_strict;                     ## yes
278
279       print(SCALAR)
280
281       The method print() prints the contents of the named variable.  If no
282       variable is given, then it prints the last variable that was used in a
283       call to parse which I find is a reasonable default.
284
285           e.g.
286
287           $tpl->parse(MAIN => "main");
288           $tpl->print();         ## prints value of MAIN
289           $tpl->print("MAIN");   ## same
290
291       This method is provided for convenience.
292
293       If you need to print other than STDOUT (e.g. socket, file handle) see
294       fetch().
295

OTHER METHODS

297       fetch(SCALAR)
298
299       Returns a scalar reference to parsed data.
300
301           $tpl->parse(CONTENT   => "main");
302           my $content = $tpl->fetch("CONTENT");
303
304           print $$content;        ## print to STDOUT
305           print FILE $$content;   ## print to filehandle or pipe
306
307       clear()
308
309       Note: All of 'clear' functions are for use under mod_perl (or anywhere
310       where your scripts are persistant).  They generally aren't needed if
311       you are writing CGI scripts.
312
313       Clears the internal hash that stores data passed from calls to assign()
314       and parse().
315
316       Often clear() is at the end of a mod_perl script:
317
318           $tpl->print();
319           $tpl->clear();
320
321       clear(ARRAY)
322
323       With no arguments, all assigned or parsed variables are cleared, but if
324       passed an ARRAY of variable names, then only those variables will be
325       cleared.
326
327         e.g.
328
329         $tpl->assign(TITLE => "Welcome");
330         $tpl->clear("TITLE");                 ## title is now empty
331
332       Another way of achieving the same effect of clearnign variables is to
333       just assign an empty string.
334
335         e.g.
336
337         $tpl->assign(TITLE => '');           ## same as: $tpl->clear("TITLE");
338
339       clear_parse()
340
341       See: clear()
342
343       clear_href(NUMBER)
344
345       Removes a given number of hash references from the list of hash refs
346       that is built using:
347
348           $tpl->assign(HASH REF);
349
350       If called with no arguments, it removes all hash references from the
351       array.  This is often used for database queries where each row from the
352       query is a hash or hash reference.
353
354       e.g.
355
356           while($hash_row = $sth->fetchrow_hashref)
357           {
358               $tpl->assign($hash_row);
359               $tpl->parse(ROW => ".row");
360               $tpl->clear_href(1);
361           }
362
363       clear_define()
364
365       Clears the internal hash that stores data passed to:
366
367           $tpl->define();
368
369       Note: The hash that holds the loaded templates is not touched with this
370       method.  See: clear_tpl
371
372       clear_tpl() clear_tpl(NAME)
373
374       The first time a template is used, it is loaded and stored in a hash in
375       memory.  clear_tpl() removes all the templates being held in memory.
376       clear_tpl(NAME) only removes the one with NAME.  This is generally not
377       required for normal CGI programming, but if you have long running
378       scripts (e.g. mod_perl) and have very large templates that a re infre‐
379       quently used gives you some control over how memory is being used.
380
381       clear_all()
382
383       Cleans the module of any data, except for the ROOT directory.  Equiva‐
384       lent to:
385
386           $tpl->clear_define();
387           $tpl->clear_href();
388           $tpl->clear_tpl();
389           $tpl->clear_parse();
390
391       Variables
392
393       A variable is defined as:
394
395           $[A-Z0-9][A-Z0-9_]+
396
397       This means, that a variable must begin with a dollar sign '$'.  The
398       second character must be an uppercase letter or digit 'A-Z0-9'.
399       Remaining characters can include an underscore.
400
401       As of version 1.07 variables can also be delimited by curly brackets.
402
403           ${[A-Z0-9][A-Z0-9_]+}
404
405       For example, the following are valid variables:
406
407           $FOO
408           $F123F
409           $TOP_OF_PAGE
410           ${NEW_STYLE}
411
412       Variable Interpolation (Template Parsing)
413
414       When the a template is being scanned for variables, pattern matching is
415       greedy. (For more info on "greediness" of regexps see perlre.)  This is
416       important, because if there are valid variable characters after your
417       variable, FastTemplate will consider them to be part of the variable.
418       As of version 1.07 you can use curly brackets as delimiters for your
419       variable names.  e.g. ${VARIABLE}  You do not need to use curly brack‐
420       ets if the character immediately after your variable name is not an
421       uppercase letter, digit or underscore.  ['A-Z0-9_']
422
423       If a variable cannot be resolved to a value then there are two possi‐
424       bilities.  If strict() has been called (it is on by default) then the
425       variable remains and a warning is printed to STDERR.   If no_strict()
426       has been called then the variables is converted to an empty string
427       [''].
428
429       See strict() and no_strict() for more info.
430
431       Some examples will make this clearer.
432
433           Assume:
434
435           $FOO = "foo";
436           $BAR = "bar";
437           $ONE = "1";
438           $TWO = "2";
439           $UND = "_";
440
441           Variable        Interpolated/Parsed
442           ------------------------------------------------
443           $FOO            foo
444           $FOO-$BAR       foo-bar
445           $ONE_$TWO       2             ## $ONE_ is undefined!
446           $ONE_$TWO       $ONE_2        ## assume: strict()
447           $ONE$UND$TWO    1_2           ## kludge!
448           ${ONE}_$TWO     1_2           ## much better
449           $$FOO           $foo
450           $25,000         $25,000
451
452       FULL EXAMPLE
453
454       This example will build an HTML page that will consist of a table.  The
455       table will have 3 numbered rows.  The first step is to decide what tem‐
456       plates we need.  In order to make it easy for the table to change to a
457       different number of rows, we will have a template for the rows of the
458       table, another for the table, and a third for the head/body part of the
459       HTML page.
460
461       Below are the templates. (Pretend each one is in a separate file.)
462
463         <!-- NAME: main.tpl -->
464         <html>
465         <head><title>$TITLE</title>
466         </head>
467         <body>
468         $MAIN
469         </body>
470         </html>
471         <!-- END: main.tpl -->
472
473         <!-- NAME: table.tpl -->
474         <table>
475         $ROWS
476         </table>
477         <!-- END: table.tpl -->
478
479         <!-- NAME: row.tpl -->
480         <tr>
481         <td>$NUMBER</td>
482         <td>$BIG_NUMBER</td>
483         </tr>
484         <!-- END: row.tpl -->
485
486       Now we can start coding...
487
488         ## START ##
489
490         use CGI::FastTemplate;
491         my $tpl = new CGI::FastTemplate("/path/to/template/files");
492
493         $tpl->define(     main    => "main.tpl",
494                           table   => "table.tpl",
495                           row     => "row.tpl",
496                           );
497
498         $tpl->assign(TITLE => "FastTemplate Test");
499
500         for $n (1..3)
501         {
502               $tpl->assign(   NUMBER      => $n,
503               BIG_NUMBER   => $n*10);
504               $tpl->parse(ROWS   => ".row");
505         }
506
507         $tpl->parse(MAIN => ["table", "main"]);
508         $tpl->print();
509
510         ## END ##
511
512         When run it returns:
513
514         <!-- NAME: main.tpl -->
515         <html>
516         <head><title>FastTemplate Test</title>
517         </head>
518         <body>
519         <!-- NAME: table.tpl -->
520         <table>
521         <!-- NAME: row.tpl -->
522         <tr>
523         <td>1</td>
524         <td>10</td>
525         </tr>
526         <!-- END: row.tpl -->
527         <!-- NAME: row.tpl -->
528         <tr>
529         <td>2</td>
530         <td>20</td>
531         </tr>
532         <!-- END: row.tpl -->
533         <!-- NAME: row.tpl -->
534         <tr>
535         <td>3</td>
536         <td>30</td>
537         </tr>
538         <!-- END: row.tpl -->
539
540         </table>
541         <!-- END: table.tpl -->
542
543         </body>
544         </html>
545         <!-- END: main.tpl -->
546
547       If you're thinking you could have done the same thing in a few lines of
548       plain perl, well yes you probably could.  But, how would a graphic
549       designer tweak the resulting HTML?  How would you have a designer edit‐
550       ing the HTML while you're editing another part of the code?  How would
551       you save the output to a file, or pipe it to another application (e.g.
552       sendmail)?  How would you make your application multi-lingual?  How
553       would you build an application that has options for high graphics, or
554       text-only?  FastTemplate really starts to shine when you are building
555       mid to large scale web applications, simply because it begins to sepa‐
556       rate the application's generic logic from the specific implementation.
557
559               Copyright (c) 1998-99 Jason Moore <jmoore@sober.com>.  All rights
560               reserved.
561
562               This program is free software; you can redistribute it and/or
563               modify it under the same terms as Perl itself.
564
565               This program is distributed in the hope that it will be useful,
566               but WITHOUT ANY WARRANTY; without even the implied warranty of
567               MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
568               Artistic License for more details.
569

AUTHOR

571       Jason Moore <jmoore@sober.com>
572

SEE ALSO

574       mod_perl(1).
575
576
577
578perl v5.8.8                       1999-06-27                   FastTemplate(3)
Impressum