1Template::Parser(3)   User Contributed Perl Documentation  Template::Parser(3)
2
3
4

NAME

6       Template::Parser - LALR(1) parser for compiling template documents
7

SYNOPSIS

9           use Template::Parser;
10
11           $parser   = Template::Parser->new(\%config);
12           $template = $parser->parse($text)
13               ⎪⎪ die $parser->error(), "\n";
14

DESCRIPTION

16       The Template::Parser module implements a LALR(1) parser and associated
17       methods for parsing template documents into Perl code.
18

PUBLIC METHODS

20       new(\%params)
21
22       The new() constructor creates and returns a reference to a new Tem‐
23       plate::Parser object.  A reference to a hash may be supplied as a
24       parameter to provide configuration values.  These may include:
25
26       START_TAG, END_TAG
27           The START_TAG and END_TAG options are used to specify character
28           sequences or regular expressions that mark the start and end of a
29           template directive.  The default values for START_TAG and END_TAG
30           are '[%' and '%]' respectively, giving us the familiar directive
31           style:
32
33               [% example %]
34
35           Any Perl regex characters can be used and therefore should be
36           escaped (or use the Perl "quotemeta" function) if they are intended
37           to represent literal characters.
38
39               my $parser = Template::Parser->new({
40                   START_TAG => quotemeta('<+'),
41                   END_TAG   => quotemeta('+>'),
42               });
43
44           example:
45
46               <+ INCLUDE foobar +>
47
48           The TAGS directive can also be used to set the START_TAG and
49           END_TAG values on a per-template file basis.
50
51               [% TAGS <+ +> %]
52
53       TAG_STYLE
54           The TAG_STYLE option can be used to set both START_TAG and END_TAG
55           according to pre-defined tag styles.
56
57               my $parser = Template::Parser->new({
58                   TAG_STYLE => 'star',
59               });
60
61           Available styles are:
62
63               template    [% ... %]               (default)
64               template1   [% ... %] or %% ... %%  (TT version 1)
65               metatext    %% ... %%               (Text::MetaText)
66               star        [* ... *]               (TT alternate)
67               php         <? ... ?>               (PHP)
68               asp         <% ... %>               (ASP)
69               mason       <% ...  >               (HTML::Mason)
70               html        <!-- ... -->            (HTML comments)
71
72           Any values specified for START_TAG and/or END_TAG will over-ride
73           those defined by a TAG_STYLE.
74
75           The TAGS directive may also be used to set a TAG_STYLE
76
77               [% TAGS html %]
78               <!-- INCLUDE header -->
79
80       PRE_CHOMP, POST_CHOMP
81           Anything outside a directive tag is considered plain text and is
82           generally passed through unaltered (but see the INTERPOLATE
83           option).  This includes all whitespace and newlines characters sur‐
84           rounding directive tags.  Directives that don't generate any output
85           will leave gaps in the output document.
86
87           Example:
88
89               Foo
90               [% a = 10 %]
91               Bar
92
93           Output:
94
95               Foo
96
97               Bar
98
99           The PRE_CHOMP and POST_CHOMP options can help to clean up some of
100           this extraneous whitespace.  Both are disabled by default.
101
102               my $parser = Template::Parser-E<gt>new({
103                   PRE_CHOMP  =E<gt> 1,
104                   POST_CHOMP =E<gt> 1,
105               });
106
107           With PRE_CHOMP set to 1, the newline and whitespace preceding a
108           directive at the start of a line will be deleted.  This has the
109           effect of concatenating a line that starts with a directive onto
110           the end of the previous line.
111
112                   Foo E<lt>----------.
113
114               ,---(PRE_CHOMP)----'
115
116               `-- [% a = 10 %] --.
117
118               ,---(POST_CHOMP)---'
119
120               `-E<gt> Bar
121
122           With POST_CHOMP set to 1, any whitespace after a directive up to
123           and including the newline will be deleted.  This has the effect of
124           joining a line that ends with a directive onto the start of the
125           next line.
126
127           If PRE_CHOMP or POST_CHOMP is set to 2, all whitespace including
128           any number of newline will be removed and replaced with a single
129           space.  This is useful for HTML, where (usually) a contiguous block
130           of whitespace is rendered the same as a single space.
131
132           With PRE_CHOMP or POST_CHOMP set to 3, all adjacent whitespace
133           (including newlines) will be removed entirely.
134
135           These values are defined as CHOMP_NONE, CHOMP_ONE, CHOMP_COLLAPSE
136           and CHOMP_GREEDY constants in the Template::Constants module.
137           CHOMP_ALL is also defined as an alias for CHOMP_ONE to provide
138           backwards compatability with earlier version of the Template Tool‐
139           kit.
140
141           Additionally the chomp tag modifiers listed below may also be used
142           for the PRE_CHOMP and POST_CHOMP configuration.
143
144                my $template = Template-E<gt>new({
145                   PRE_CHOMP  =E<lt> '~',
146                   POST_CHOMP =E<gt> '-',
147                });
148
149           PRE_CHOMP and POST_CHOMP can be activated for individual directives
150           by placing a '-' immediately at the start and/or end of the direc‐
151           tive.
152
153               [% FOREACH user IN userlist %]
154                  [%- user -%]
155               [% END %]
156
157           This has the same effect as CHOMP_ONE in removing all whitespace
158           before or after the directive up to and including the newline.  The
159           template will be processed as if written:
160
161               [% FOREACH user IN userlist %][% user %][% END %]
162
163           To remove all whitespace including any number of newlines, use the
164           '~' character instead.
165
166               [% FOREACH user IN userlist %]
167
168                  [%~ user ~%]
169
170               [% END %]
171
172           To collapse all whitespace to a single space, use the '=' charac‐
173           ter.
174
175               [% FOREACH user IN userlist %]
176
177                  [%= user =%]
178
179               [% END %]
180
181           Here the template is processed as if written:
182
183               [% FOREACH user IN userlist %] [% user %] [% END %]
184
185           If you have PRE_CHOMP or POST_CHOMP set as configuration options
186           then you can use '+' to disable any chomping options (i.e.  leave
187           the whitespace intact) on a per-directive basis.
188
189               [% FOREACH user = userlist %]
190               User: [% user +%]
191               [% END %]
192
193           With POST_CHOMP set to CHOMP_ONE, the above example would be parsed
194           as if written:
195
196               [% FOREACH user = userlist %]User: [% user %]
197               [% END %]
198
199           For reference, the PRE_CHOMP and POST_CHOMP configuration options
200           may be set to any of the following:
201
202                Constant      Value   Tag Modifier
203                ----------------------------------
204                CHOMP_NONE      0          +
205                CHOMP_ONE       1          -
206                CHOMP_COLLAPSE  2          =
207                CHOMP_GREEDY    3          ~
208
209       INTERPOLATE
210           The INTERPOLATE flag, when set to any true value will cause vari‐
211           able references in plain text (i.e. not surrounded by START_TAG and
212           END_TAG) to be recognised and interpolated accordingly.
213
214               my $parser = Template::Parser->new({
215                   INTERPOLATE => 1,
216               });
217
218           Variables should be prefixed by a '$' to identify them.  Curly
219           braces can be used in the familiar Perl/shell style to explicitly
220           scope the variable name where required.
221
222               # INTERPOLATE => 0
223               <a href="http://[% server %]/[% help %]">
224               <img src="[% images %]/help.gif"></a>
225               [% myorg.name %]
226
227               # INTERPOLATE => 1
228               <a href="http://$server/$help">
229               <img src="$images/help.gif"></a>
230               $myorg.name
231
232               # explicit scoping with {  }
233               <img src="$images/${icon.next}.gif">
234
235           Note that a limitation in Perl's regex engine restricts the maximum
236           length of an interpolated template to around 32 kilobytes or possi‐
237           bly less.  Files that exceed this limit in size will typically
238           cause Perl to dump core with a segmentation fault.  If you rou‐
239           tinely process templates of this size then you should disable
240           INTERPOLATE or split the templates in several smaller files or
241           blocks which can then be joined backed together via PROCESS or
242           INCLUDE.
243
244       ANYCASE
245           By default, directive keywords should be expressed in UPPER CASE.
246           The ANYCASE option can be set to allow directive keywords to be
247           specified in any case.
248
249               # ANYCASE => 0 (default)
250               [% INCLUDE foobar %]        # OK
251               [% include foobar %]        # ERROR
252               [% include = 10   %]        # OK, 'include' is a variable
253
254               # ANYCASE => 1
255               [% INCLUDE foobar %]        # OK
256               [% include foobar %]        # OK
257               [% include = 10   %]        # ERROR, 'include' is reserved word
258
259           One side-effect of enabling ANYCASE is that you cannot use a vari‐
260           able of the same name as a reserved word, regardless of case.  The
261           reserved words are currently:
262
263                   GET CALL SET DEFAULT INSERT INCLUDE PROCESS WRAPPER
264               IF UNLESS ELSE ELSIF FOR FOREACH WHILE SWITCH CASE
265               USE PLUGIN FILTER MACRO PERL RAWPERL BLOCK META
266               TRY THROW CATCH FINAL NEXT LAST BREAK RETURN STOP
267               CLEAR TO STEP AND OR NOT MOD DIV END
268
269           The only lower case reserved words that cannot be used for vari‐
270           ables, regardless of the ANYCASE option, are the operators:
271
272               and or not mod div
273
274       V1DOLLAR
275           In version 1 of the Template Toolkit, an optional leading '$' could
276           be placed on any template variable and would be silently ignored.
277
278               # VERSION 1
279               [% $foo %]       ===  [% foo %]
280               [% $hash.$key %] ===  [% hash.key %]
281
282           To interpolate a variable value the '${' ... '}' construct was
283           used.  Typically, one would do this to index into a hash array when
284           the key value was stored in a variable.
285
286           example:
287
288               my $vars = {
289                   users => {
290                       aba => { name => 'Alan Aardvark', ... },
291                       abw => { name => 'Andy Wardley', ... },
292                       ...
293                   },
294                   uid => 'aba',
295                   ...
296               };
297
298               $template->process('user/home.html', $vars)
299                   ⎪⎪ die $template->error(), "\n";
300
301           'user/home.html':
302
303               [% user = users.${uid} %]     # users.aba
304               Name: [% user.name %]         # Alan Aardvark
305
306           This was inconsistent with double quoted strings and also the
307           INTERPOLATE mode, where a leading '$' in text was enough to indi‐
308           cate a variable for interpolation, and the additional curly braces
309           were used to delimit variable names where necessary.  Note that
310           this use is consistent with UNIX and Perl conventions, among oth‐
311           ers.
312
313               # double quoted string interpolation
314               [% name = "$title ${user.name}" %]
315
316               # INTERPOLATE = 1
317               <img src="$images/help.gif"></a>
318               <img src="$images/${icon.next}.gif">
319
320           For version 2, these inconsistencies have been removed and the syn‐
321           tax clarified.  A leading '$' on a variable is now used exclusively
322           to indicate that the variable name should be interpolated (e.g.
323           subsituted for its value) before being used.  The earlier example
324           from version 1:
325
326               # VERSION 1
327               [% user = users.${uid} %]
328               Name: [% user.name %]
329
330           can now be simplified in version 2 as:
331
332               # VERSION 2
333               [% user = users.$uid %]
334               Name: [% user.name %]
335
336           The leading dollar is no longer ignored and has the same effect of
337           interpolation as '${' ... '}' in version 1.  The curly braces may
338           still be used to explicitly scope the interpolated variable name
339           where necessary.
340
341           e.g.
342
343               [% user = users.${me.id} %]
344               Name: [% user.name %]
345
346           The rule applies for all variables, both within directives and in
347           plain text if processed with the INTERPOLATE option.  This means
348           that you should no longer (if you ever did) add a leading '$' to a
349           variable inside a directive, unless you explicitly want it to be
350           interpolated.
351
352           One obvious side-effect is that any version 1 templates with vari‐
353           ables using a leading '$' will no longer be processed as expected.
354           Given the following variable definitions,
355
356               [% foo = 'bar'
357                  bar = 'baz'
358               %]
359
360           version 1 would interpret the following as:
361
362               # VERSION 1
363               [% $foo %] => [% GET foo %] => bar
364
365           whereas version 2 interprets it as:
366
367               # VERSION 2
368               [% $foo %] => [% GET $foo %] => [% GET bar %] => baz
369
370           In version 1, the '$' is ignored and the value for the variable
371           'foo' is retrieved and printed.  In version 2, the variable '$foo'
372           is first interpolated to give the variable name 'bar' whose value
373           is then retrieved and printed.
374
375           The use of the optional '$' has never been strongly recommended,
376           but to assist in backwards compatibility with any version 1 tem‐
377           plates that may rely on this "feature", the V1DOLLAR option can be
378           set to 1 (default: 0) to revert the behaviour and have leading '$'
379           characters ignored.
380
381               my $parser = Template::Parser->new({
382                   V1DOLLAR => 1,
383               });
384
385       GRAMMAR
386           The GRAMMAR configuration item can be used to specify an alternate
387           grammar for the parser.  This allows a modified or entirely new
388           template language to be constructed and used by the Template Tool‐
389           kit.
390
391           Source templates are compiled to Perl code by the Template::Parser
392           using the Template::Grammar (by default) to define the language
393           structure and semantics.  Compiled templates are thus inherently
394           "compatible" with each other and there is nothing to prevent any
395           number of different template languages being compiled and used
396           within the same Template Toolkit processing environment (other than
397           the usual time and memory constraints).
398
399           The Template::Grammar file is constructed from a YACC like grammar
400           (using Parse::YAPP) and a skeleton module template.  These files
401           are provided, along with a small script to rebuild the grammar, in
402           the 'parser' sub-directory of the distribution.  You don't have to
403           know or worry about these unless you want to hack on the template
404           language or define your own variant.  There is a README file in the
405           same directory which provides some small guidance but it is assumed
406           that you know what you're doing if you venture herein.  If you grok
407           LALR parsers, then you should find it comfortably familiar.
408
409           By default, an instance of the default Template::Grammar will be
410           created and used automatically if a GRAMMAR item isn't specified.
411
412               use MyOrg::Template::Grammar;
413
414               my $parser = Template::Parser->new({
415                   GRAMMAR = MyOrg::Template::Grammar->new();
416               });
417
418       DEBUG
419           The DEBUG option can be used to enable various debugging features
420           of the Template::Parser module.
421
422               use Template::Constants qw( :debug );
423
424               my $template = Template->new({
425                   DEBUG => DEBUG_PARSER ⎪ DEBUG_DIRS,
426               });
427
428           The DEBUG value can include any of the following.  Multiple values
429           should be combined using the logical OR operator, '⎪'.
430
431           DEBUG_PARSER
432               This flag causes the Template::Parser to generate debugging
433               messages that show the Perl code generated by parsing and com‐
434               piling each template.
435
436           DEBUG_DIRS
437               This option causes the Template Toolkit to generate comments
438               indicating the source file, line and original text of each
439               directive in the template.  These comments are embedded in the
440               template output using the format defined in the DEBUG_FORMAT
441               configuration item, or a simple default format if unspecified.
442
443               For example, the following template fragment:
444
445                   Hello World
446
447               would generate this output:
448
449                   ## input text line 1 :  ##
450                   Hello
451                   ## input text line 2 : World ##
452                   World
453
454       parse($text)
455
456       The parse() method parses the text passed in the first parameter and
457       returns a reference to a hash array of data defining the compiled rep‐
458       resentation of the template text, suitable for passing to the Tem‐
459       plate::Document new() constructor method.  On error, undef is returned.
460
461       Example:
462
463           $data = $parser->parse($text)
464               ⎪⎪ die $parser->error();
465
466       The $data hash reference returned contains a BLOCK item containing the
467       compiled Perl code for the template, a DEFBLOCKS item containing a ref‐
468       erence to a hash array of sub-template BLOCKs defined within in the
469       template, and a METADATA item containing a reference to a hash array of
470       metadata values defined in META tags.
471

AUTHOR

473       Andy Wardley <abw@wardley.org>
474
475       <http://wardley.org/http://wardley.org/>
476

VERSION

478       2.89, distributed as part of the Template Toolkit version 2.18,
479       released on 09 February 2007.
480
482         Copyright (C) 1996-2007 Andy Wardley.  All Rights Reserved.
483
484       This module is free software; you can redistribute it and/or modify it
485       under the same terms as Perl itself.
486
487       The original Template::Parser module was derived from a standalone
488       parser generated by version 0.16 of the Parse::Yapp module.  The fol‐
489       lowing copyright notice appears in the Parse::Yapp documentation.
490
491           The Parse::Yapp module and its related modules and shell
492           scripts are copyright (c) 1998 Francois Desarmenien,
493           France. All rights reserved.
494
495           You may use and distribute them under the terms of either
496           the GNU General Public License or the Artistic License, as
497           specified in the Perl README file.
498

SEE ALSO

500       Template, Template::Grammar, Template::Directive
501
502
503
504perl v5.8.8                       2007-02-09               Template::Parser(3)
Impressum