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

NAME

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

CORE METHODS

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

OTHER METHODS

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

AUTHOR

552       Jason Moore <jmoore@sober.com>
553

SEE ALSO

555       mod_perl(1).
556
557
558
559perl v5.36.0                      2022-07-22                   FastTemplate(3)
Impressum