1Parse::Template(3) User Contributed Perl Documentation Parse::Template(3)
2
3
4
6 Parse::Template - Processor for templates containing Perl expressions
7
9 use Parse::Template;
10
11 my %template =
12 (
13 'TOP' => q!Text before %%$self->eval('DATA')%% text after!,
14 'DATA' => q!Insert data: ! .
15 q!1. List: %%"@list$N"%%! .
16 q!2. Hash: %%"$hash{'key'}$N"%%! .
17 q!3. File content: %%<FH>%%! .
18 q!4. Sub: %%&SUB()$N%%!
19 );
20
21 my $tmplt = new Parse::Template (%template);
22 open FH, "< foo";
23
24 $tmplt->env('var' => '(value!)');
25 $tmplt->env('list' => [1, 2, 10],
26 'N' => "\n",
27 'FH' => \*FH,
28 'SUB' => sub { "->content generated by a sub<-" },
29 'hash' => { 'key' => q!It\'s an hash value! });
30 print $tmplt->eval('TOP'), "\n";
31
33 The "Parse::Template" class evaluates Perl expressions placed within a
34 text. This class can be used as a code generator, or a generator of
35 documents in various document formats (HTML, XML, RTF, etc.).
36
37 The principle of template-based text generation is simple. A template
38 consists of a text which includes expressions to be evaluated.
39 Interpretation of these expressions generates text fragments which are
40 substituted in place of the expressions. In the case of
41 "Parse::Template" the expressions to be evaluated are Perl expressions
42 placed within two "%%".
43
44 Evaluation takes place within an environment in which, for example, you
45 can place data structures which will serve to generate the parts to be
46 completed.
47
48 TEMPLATE
49 Text + Perl Expression
50 |
51 +-----> Evaluation ----> Text(document or program)
52 |
53 Subs + Data structures
54 ENVIRONMENT
55
56 The "Parse::Template" class permits decomposing a template into parts.
57 These parts are defined by a hash passed as an argument to the class
58 constructor: "Parse::Template-">"new('someKey', '... text with
59 expressions to evaluate ...')". Within a part, a sub-part can be
60 included by means of an expression of the form:
61
62 $self->eval('SUB_PART_NAME')
63
64 $self designates the instance of the "Parse::Template" class. In an
65 expression you can also use the $part which contains the part of the
66 template where the expression is found.
67
68 Within an expression it is possible to specify only the name of a part
69 to be inserted. In this case a subroutine with the name of this part
70 is generated dynamically. In the example given in the synopsis, the
71 insertion of the "TOP" part can thus be rewritten as follows:
72
73 'TOP' => q!Text before %%DATA()%% text after!
74
75 "DATA()" is placed within "%%" and is in effect treated as an
76 expression to be evaluated.
77
78 The subroutines take arguments. In the following example, the argument
79 is used to control the depth of recursive calls of a template:
80
81 print Parse::Template->new(
82 'TOP' => q!%%$_[0] < 10 ? '[' . TOP($_[0] + 1) . ']' : ''%%!
83 )->eval('TOP', 0);
84
85 $_[0] initially contains 0. "TOP" is included as long as the argument
86 is less than 10. For each inclusion, 1 is added to the argument.
87
88 The "env()" method permits constructing the environment required for
89 evaluation of a template. Each entry to be defined within this
90 environment must be specified using a key consisting of the name of the
91 symbol to be created, associated with a reference whose type is that of
92 the entry to be created within this environment (for example, a
93 reference to an array to create an array). A scalar variable is
94 defined by associating the name of the variable with its value. A
95 scalar variable containing a reference is defined by writing
96 "'var'=">"\$variable", where $variable is a lexical variable that
97 contains the reference.
98
99 Each instance of "Parse::Template" is defined within a specific class,
100 a subclass of "Parse::Template". The subclass contains the environment
101 specific to the template and inherits methods from the
102 "Parse::Template" class.
103
104 If a template is created from an existing template (i.e. calling "new"
105 as a method of the existing template), it inherits all the parts
106 defined by its ancestor.
107
108 In case of a syntax error in the evalutaion of an expression,
109 "Parse::Template" tries to indicate the template part and the
110 expression that is "incriminated". If the variable
111 $Parse::Template::CONFESS contains the value TRUE, the stack of
112 evaluations is printed.
113
115 new HASH
116 Constructor for the class. "HASH" is a hash which defines the
117 template text.
118
119 Example:
120
121 use Parse::Template;
122 $t = new Parse::Template('key' => 'associated text');
123
124 env HASH
125 env SYMBOL
126 Permits defining the environment that is specific to a template.
127
128 "env(SYMBOL)" returns the reference associated with the symbol, or
129 "undef" if the symbol is not defined. The reference that is
130 returned is of the type indicated by the character ("&, $, %, @,
131 *") that prefixes the symbol.
132
133 Examples:
134
135 $tmplt->env('LIST' => [1, 2, 3])} Defines a list
136
137 @{$tmplt->env('*LIST')} Returns the list
138
139 @{$tmplt->env('@LIST')} Ditto
140
141 eval PART_NAME
142 Evaluates the template part designated by "PART_NAME". Returns the
143 string resulting from this evaluation.
144
145 getPart PART_NAME
146 Returns the designated part of the template.
147
148 ppregexp REGEXP
149 Preprocesses a regular expression so that it can be inserted into a
150 template where the regular expression delimiter is either a "/" or
151 a "!".
152
153 setPart PART_NAME => TEXT
154 "setPart()" permits defining a new entry in the hash that defines
155 the contents of the template.
156
158 The "Parse::Template" class can be used in all sorts of amusing ways.
159 Here are a few illustrations.
160
161 HTML Generator
162 The first example shows how to generate an HTML document by using a
163 data structure placed within the evaluation environment. The template
164 consists of two parts, "DOC" and "SECTION". The "SECTION" part is
165 called within the "DOC" part to generate as many sections as there are
166 elements in the array "section_content".
167
168 my %template = ('DOC' => <<'END_OF_DOC;', 'SECTION' => <<'END_OF_SECTION;');
169 <html>
170 <head></head>
171 <body>
172 %%
173 my $content;
174 for (my $i = 0; $i <= $#section_content; $i++) {
175 $content .= SECTION($i);
176 }
177 $content;
178 %%
179 </body>
180 </html>
181 END_OF_DOC;
182 %%
183 $section_content[$_[0]]->{Content} =~ s/^/<p>/mg;
184 join '', '<H1>', $section_content[$_[0]]->{Title}, '</H1>',
185 $section_content[$_[0]]->{Content};
186 %%
187 END_OF_SECTION;
188
189 my $tmplt = new Parse::Template (%template);
190
191 $tmplt->env('section_content' => [
192 {
193 Title => 'First Section',
194 Content => 'Nothing to write'
195 },
196 {
197 Title => 'Second section',
198 Content => 'Nothing else to write'
199 }
200 ]
201 );
202
203 print $tmplt->eval('DOC'), "\n";
204
205 HTML generation using functional notation
206 The second example shows how to generate an HTML document using a
207 functional notation, in other words, obtaining the text:
208
209 <P><B>text in bold</B><I>text in italic</I></P>
210
211 from:
212
213 P(B("text in bold"), I("text in italic"))
214
215 The functions P(), B() and I() are defined as parts of a template. The
216 Perl expression that permits producing the content of an element is
217 very simple, and reduces to:
218
219 join '', @_
220
221 The content to be evaluated is the same regardless of the tag and can
222 therefore be placed within a variable. We therefore obtain the
223 following template:
224
225 my $ELT_CONTENT = q!%%join '', @_%%!;
226 my $HTML_T1 = new Parse::Template(
227 'DOC' => '%%P(B("text in bold"), I("text in italic"))%%',
228 'P' => qq!<P>$ELT_CONTENT</P>!,
229 'B' => qq!<B>$ELT_CONTENT</B>!,
230 'I' => qq!<I>$ELT_CONTENT</I>!,
231 );
232 print $HTML_T1->eval('DOC'), "\n";
233
234 We can go further by making use of the $part variable, which is defined
235 by default in the environment of evaluation of the template:
236
237 my $ELT_CONTENT = q!%%"<$part>" . join('', @_) . "</$part>"%%!;
238 my $HTML_T2 = new Parse::Template(
239 'DOC' => '%%P(B("text in bold"), I("text in italic"))%%',
240 'P' => qq!$ELT_CONTENT!,
241 'B' => qq!$ELT_CONTENT!,
242 'I' => qq!$ELT_CONTENT!,
243 );
244 print $HTML_T2->eval('DOC'), "\n";
245
246 Let's look at another step which automates the production of
247 expressions from the list of HTML tags which are of interest to us:
248
249 my $DOC = q!P(B("text in bold"), I("text in italic"))!;
250 my $ELT_CONTENT = q!%%"<$part>" . join('', @_) . "</$part>"%%!;
251 my $HTML_T3 = new Parse::Template(
252 'DOC' => qq!%%$DOC%%!,
253 map { $_ => $ELT_CONTENT } qw(P B I)
254 );
255 print $HTML_T3->eval('DOC'), "\n";
256
257 To benefit from the possibility of using the template parts as
258 procedures, we can inherit from the generated template class:
259
260 use Parse::Template;
261 my $ELT_CONTENT = q!%%"<$part>" . join('', @_) . "</$part>"%%!;
262 my $G = new Parse::Template(
263 map { $_ => $ELT_CONTENT } qw(H1 B I)
264 );
265 @main::ISA = ref($G);
266 *AUTOLOAD = \&Parse::Template::AUTOLOAD;
267 print H1(B("text in bold"), I("text in italic"));
268
269 The reference to "Parse::Template::AUTOLOAD" avoids the warning
270 message:
271
272 Use of inherited AUTOLOAD for non-method %s() is deprecated
273
274 Not very elegant.
275
276 HTML generation by method call
277 With a slight transformation it is possible to use a method-invocation
278 notation:
279
280 my $ELT_CONTENT = q!%%shift(@_); "<$part>" . join('', @_) . "</$part>"%%!;
281 my $HTML_T4 = new Parse::Template(
282 map { $_ => $ELT_CONTENT } qw(P B I)
283 );
284 print $HTML_T4->P(
285 $HTML_T4->B("text in bold"),
286 $HTML_T4->I("text in italic")
287 ), "\n";
288
289 The "shift(@_)" permits getting rid of the template object, which we
290 don't need within the expression.
291
292 Inheritance of parts
293 In the following example the child template $C inherits the parts
294 defined in its parent template $A:
295
296 my %ancestor =
297 (
298 'TOP' => q!%%"Use the $part model and -> " . CHILD()%%!,
299 'ANCESTOR' => q!ANCESTOR %%"'$part' part\n"%%!,
300 );
301
302 my %child =
303 (
304 'CHILD' => q!CHILD %%"'$part' part"%% -> %%ANCESTOR() . "\n"%%!,
305 );
306 my $A = new Parse::Template (%ancestor);
307 my $C = $A->new(%child);
308 print $C->TOP();
309
310 The part <TOP> defined in $A can be called directly from $C, that
311 derives from $A.
312
313 Other examples
314 "Parse::Template" was initially created to serve as a code generator
315 for the "Parse::Lex" class. You will find other examples of its use in
316 the classes "Parse::Lex", "Parse::CLex" and "Parse::Token".
317
319 I would be very interested to receive your comments and suggestions.
320
322 Instances are not destroyed. Therefore, do not use this class to
323 create a large number of instances.
324
326 Philippe Verdret (with translation of documentation into English by
327 Ocrat)
328
330 Copyright (c) 1995-2001 Philippe Verdret. All rights reserved. This
331 module is free software; you can redistribute it and/or modify it under
332 the same terms as Perl itself.
333
334
335
336perl v5.32.0 2020-07-28 Parse::Template(3)