TAL.pm untested

filter: Statementstmt 0.0% 0 / 126 Branchbran 0.0% 0 / 50 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 0.0% 0 / 19 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 240 CC 26 SCAR 39.3
CC
26
Cov
0%
_process_node
156.0
new
30.0
process
20.0
CRAP 51.0
1 =head1 NAME
2  
3 Template::TAL - Process TAL templates with Perl
4  
5 =head1 SYNOPSIS
6  
7 # create the TT object, telling it where the templates are
8 my $tt = Template::TAL->new( include_path => "./templates" );
9  
10 # data to interpolate into the template
11 my $data = {
12 foo => "bar",
13 };
14  
15 # process the template from disk (in ./templates/test.tal) with the data
16 print $tt->process("test.tal", $data);
17  
18 =head1 DESCRIPTION
19  
20 L<TAL|http://www.zope.org/Wikis/DevSite/Projects/ZPT/TAL> is a templating
21 language used in the Zope CMS. Template::TAL is a Perl implementation of
22 TAL based on the published specs on the Zope wiki.
23  
24 TAL templates are XML documents, and use attributes in the TAL namespace to
25 define how elements of the template should be treated/displayed. For example:
26  
27 my $template = <<'ENDOFXML';
28 <html xmlns:tal="http://xml.zope.org/namespaces/tal">
29 <head>
30 <title tal:content="title"/>
31 </head>
32 <body>
33 <h1>This is the <span tal:replace="title"/> page</h1>
34 <ul>
35 <li tal:repeat="user users">
36 <a href="?" tal:attributes="href user/url"><span tal:replace="user/name"/></a>
37 </li>
38 </ul>
39 </body>
40 </html>
41 ENDOFXML
42  
43 This template can be processed by passing it and the parameters to the
44 C<process> method:
45  
46 my $tt = Template::TAL->new();
47 $tt->process(\$template, {
48 title => "Bert and Ernie Fansite",
49 users => [
50 { url => "http://www.henson.com/", name => "Henson", },
51 { url => "http://www.sesameworkshop.org/", name => "Workshop", },
52 { url => "http://www.bertisevil.tv/", name => "Bert is Evil", },
53 ],
54 })
55  
56 Alternativly you can store the templates on disk, and pass the filename to
57 C<process> directly instead of via a reference (as shown in the synopsis above.)
58  
59 Template::TAL is designed to be extensible, allowing you to load templates from
60 different places and produce more than one type of output. By default the XML
61 template will be output as cross-browser compatible HTML (meaning, for example,
62 that image tags won't be closed.) Other output formats, including well-formed
63 XML, can easily be produced by changing the output class (detailed below.)
64  
65 For more infomation on the TAL spec itself, see
66 http://www.zope.org/Wikis/DevSite/Projects/ZPT/TAL%20Specification%201.4
67  
68 =cut
69  
70 package Template::TAL;
71 use warnings;
72 use strict;
73 use Carp qw( croak );
74 use UNIVERSAL::require;
75 use Scalar::Util qw( blessed );
76  
77 our $VERSION = "0.91";
78  
79 use Template::TAL::Template;
80 use Template::TAL::Provider;
81 use Template::TAL::Provider::Disk;
82 use Template::TAL::Output::XML;
83 use Template::TAL::Output::HTML;
84 use Template::TAL::ValueParser;
85  
86 =head1 METHODS
87  
88 =over
89  
90 =item new( include_path => ['/foo/bar'], charset => 'utf-8' )
91  
92 Creates and initializes a new Template::TAL object. Options valid here are:
93  
94 =over
95  
96 =item include_path
97  
98 If this parameter is set then it is passed to the provider, telling it where
99 to load files from disk (if applicable for the provider.)
100  
101 =item charset
102  
103 If this parameter is set then it is passed to the output, telling it what
104 charset to use instead of its default. The default output class will use the
105 'utf-8' charset unless you tell it otherwise.
106  
107 =item provider
108  
109 Pass a 'provider' option to specify a provider rather than using the default
110 provider that reads from disk. This can either be a class name of a loaded
111 class, or an object instance.
112  
113 =item output
114  
115 Pass a 'output' option to specify a output class rather than using the default
116 output class that dumps the DOM tree to as a string to create HTML. This can
117 either be a class name of a loaded class, or an object instance.
118  
119 =back
120  
121 =cut
122  
123 sub new {
124 my ($class, %args) = @_;
125 my $self = bless {}, $class;
126  
127 # if we've got a provider, set it
128 if (exists $args{provider}) {
129 $self->provider( delete $args{provider} );
130 }
131  
132 # if we've got an include path, pass it to the provider
133 if (exists $args{include_path}) {
134 $self->provider->include_path(delete $args{include_path});
135 }
136  
137 # if we've got an output set it
138 if (exists $args{output}) {
139 $self->output( delete $args{output} );
140 }
141  
142 # if we've got a charset, pass it to the output
143 if (exists $args{charset}) {
144 $self->output->charset( delete $args{charset} );
145 }
146  
147 $self->add_language("Template::TAL::Language::TALES");
148 $self->add_language("Template::TAL::Language::TAL");
149 $self->add_language("Template::TAL::Language::METAL");
150  
151 return $self;
152 }
153  
154 sub provider {
155 my $self = shift;
156 return $self->{provider} ||= Template::TAL::Provider::Disk->new() unless @_;
157 $self->{provider} = blessed($_[0]) ? $_[0] : $_[0]->new();
158 return $self;
159 }
160  
161 sub output {
162 my $self = shift;
163 return $self->{output} ||= Template::TAL::Output::HTML->new() unless @_;
164 $self->{output} = blessed($_[0]) ? $_[0] : $_[0]->new();
165 return $self;
166 }
167  
168 =item languages
169  
170 a listref of language plugins we will use when parsing. All
171 templates get at least the L<Template::TAL::Language:TAL> language module.
172  
173 =cut
174  
175 sub languages {
176 my $self = shift;
177 return $self->{languages} ||= [] unless @_;
178 $self->{languages} = ref($_[0]) ? shift : [ @_ ];
179 return $self;
180 }
181  
182 =item add_language( language module, module, module... )
183  
184 adds a language to the list of those used by the template renderer. 'module'
185 here can be a classname or an instance.
186  
187 =cut
188  
189 sub add_language {
190 my $self = shift;
191 for (@_) {
192 my $language = $_; # take a modifiable copy.
193 unless (ref($language)) {
194 $language->require or die "Can't load language '$language': $@";
195 $language = $language->new;
196 }
197 push @{ $self->{languages} }, $language;
198 }
199 return $self;
200 }
201  
202 =item process( $template, $data_hashref )
203  
204 Process the template with the passed data and return the resulting rendered
205 byte sequence.
206  
207 C<$template> can either be a string containing where the provider should get
208 the template from (i.e. the filename of the template in the include path), a
209 reference to a string containing the literal text of the template, or a
210 Template::TAL::Template object.
211  
212 C<$data_hashref> should be a reference to a hash containing the values that
213 are to be substituted into the template.
214  
215 =cut
216  
217 sub process {
218 my ($self, $template, $data) = @_;
219  
220 if (!ref $template) {
221 $template = $self->provider->get_template( $template )
222 } elsif (ref($template) eq 'SCALAR') {
223 # scalar reference - a reference to source of a template
224 $template = Template::TAL::Template->new->source($$template);
225 } elsif (!UNIVERSAL::isa($template, 'Template::TAL::Template')) {
226 croak("Can't understand object of type ".ref($template)." as a template");
227 }
228  
229 # walk the template, converting the DOM tree as we go. Local context
230 # starts as empty, global context is the template data.
231 my $dom = $template->document->cloneNode(1); # deep clone
232 $self->_process_node( $dom->documentElement, {}, $data );
233  
234 return $self->output->render( $dom );
235 }
236  
237 # this processes a given DOM node with the passed contexts, using the
238 # language plugins, and manipulates the DOM node
239 # according to the instructions of the plugins. Returns nothing
240 # interesting - it is expected to change the DOM tree in place.
241 #
242 # this method is private because it shouldn't be exposed to the user,
243 # but the TAL language module calls it, so it's not 'properly' private.
244 sub _process_node {
245 my ($self, $node, $local_context, $global_context) = @_;
246  
247 # we only care about handling elements - text nodes, etc, don't have
248 # attributes and therefore can't be munged.
249 return unless $node->nodeType == 1;
250  
251 # a mapping of namespaces->plugin class for fast lookup later.
252 my %namespaces = map { $_->namespace => $_ } grep { $_->namespace } @{ $self->languages };
253
254 # we have to make a distinction between local and global context,
255 # because the define tag can set into the global context. Curses.
256 $global_context ||= {};
257 $local_context ||= {};
258  
259 # make a shallow copy. Shallow is enough, because we can't set deep paths.
260 $local_context = { %$local_context };
261  
262 # record attributes of the node we're processing, but leave them
263 # in place, so recursive processing gets a chance to look at them
264 # again later
265 my %attrs; # will be $attrs{ language module namespace uri }{ tag name }
266 for my $attribute ($node->attributes) {
267 my $uri = $attribute->getNamespaceURI;
268 next unless $uri and $attribute->nodeType == 2; # attributes with namespaces only
269 if ( $namespaces{ $uri } ) {
270 # we have a handler for this namespace
271 $attrs{ $uri }{ $attribute->name } = $attribute->value;
272 }
273 }
274  
275 # If at any point something replaces the whole node, we can stop thinking,
276 # and return, as the new node is supposed to have already been processed.
277 # Record this state here.
278 my $replaced = 0;
279  
280 # for all our language classes (in order)
281 LANGUAGE: for my $language ( @{ $self->languages } ) {
282 # only process if the language is referenced.
283 next unless $language->namespace and exists $attrs{ $language->namespace };
284  
285 # the languages have an ordered list of tag types they want to deal with.
286 OPS: for my $type ($language->tags) {
287 next unless exists $attrs{ $language->namespace }{ $type };
288  
289 # remove this attribute from the node first, recursive processing
290 # wants to see all _other_ attributes, but not the one that caused
291 # the recursion in the first place.
292 $node->removeAttributeNS( $language->namespace, $type );
293
294 # handle this attribute
295 my $sub = "process_tag_$type"; $sub =~ s/\-/_/;
296 Carp::croak("language module $language can't handle nodes of type '$type', as claimed")
297 unless $language->can($sub);
298 my @replace = $language->$sub($self, $node, $attrs{ $language->namespace }{ $type }, $local_context, $global_context);
299
300 # remove from the todo list, so we can track unhandled attributes later.
301 delete $attrs{ $language->namespace }{ $type };
302
303 # if we're replacing the node with something else as a result of the
304 # attribute, do so. Once we've done that, we're finished, so leave.
305 if (!@replace) {
306 # remove the node
307 $node->parentNode->removeChild( $node );
308 $replaced = 1;
309
310 } elsif (@replace and $replace[0] != $node) {
311 # replacing with something else. There's no nice 'replace this
312 # single node with this list of nodes' operator, so we need this
313 # fairly nasty cludge.
314 my $this = shift @replace;
315 $node->replaceNode($this);
316 for (@replace) {
317 $this->parentNode->insertAfter($_, $this);
318 $this = $_;
319 }
320 $replaced = 1;
321 }
322
323 if ($replaced) {
324 delete $attrs{ $language->namespace }; # because the handler will have dealt with them
325 last LANGUAGE; # there's no point.
326 }
327  
328 } # ops loop
329  
330 # complain about any other attributes on the node
331 warn sprintf("unhandled TAL attributes '%s' in namespace '%s' on element '%s' at line %d\n",
332 join(',', keys %{ $attrs{ $language->namespace } }),
333 $language->namespace, $node->nodeName, $node->line_number)
334 if %{ $attrs{ $language->namespace } };
335  
336 } # languages loop
337
338  
339 # now recurse into child nodes, unless we replaced the current node, in
340 # which case we assume that it's been dealt with.
341 unless ($replaced) {
342 for my $child ( $node->childNodes() ) {
343 $self->_process_node( $child, $local_context, $global_context );
344 }
345 }
346 }
347  
348 =item parse_tales( value, context, context,... )
349  
350 Parses a TALES string (see http://www.zope.org/Wikis/DevSite/Projects/ZPT/TALES),
351 looking in each of the passed contexts in order for variable values, and returns
352 the value.
353  
354 =cut
355  
356 sub parse_tales {
357 my ($self, $value, @contexts) = @_;
358 return Template::TAL::ValueParser->value($value, \@contexts, $self->languages);
359 }
360  
361 =back
362  
363 =head1 ATTRIBUTES
364  
365 These are get/set chained accessor methods that can be used to alter the object
366 after initilisation (meaning they return their value when called without
367 arguments, and set the value and return $self when called with.)
368  
369 In both cases you can set these to either class names or actual instances
370 and they with do the right thing.
371  
372 =over
373  
374 =item provider
375  
376 The instance of the L<Template::TAL::Provider> subclass that will be providing
377 templates to this engine.
378  
379 =item output
380  
381 The instance of the L<Template::TAL::Output> subclass that will be used to
382 render the produced template output.
383  
384 =back
385  
386 =head1 RATIONALE
387  
388 L<Petal> is another Perl module that can process a templating language
389 suspiciously similar to TAL. So why did we implement Yet Another
390 Templating Engine? Well, we liked Petal a lot. However, at the time of
391 writing our concerns with Petal were:
392  
393 =over
394  
395 =item
396  
397 Petal isn't strictly TAL. We consider this a flaw.
398  
399 =item
400  
401 Petal assumes rather strongly that templates are stored on disk. We wanted
402 a system with a pluggable template source so that we could store templates
403 in other places (such as a database.)
404  
405 =item
406  
407 Petal does lots of caching. This is a good thing if you've got a small
408 number of templates compared to the number of pages you serve. However, if
409 you've got a vast number of templates - more than you can hold in memory -
410 then this quickly becomes self defeating. We wanted code that doesn't have
411 any caching in it at all.
412  
413 =back
414  
415 In conclusion: You may be better off using Petal. Certainly the caching
416 layer could be very useful to you.
417  
418 There's more than one way to do it.
419  
420 =head1 COPYRIGHT
421  
422 Written by Tom Insam, Copyright 2005 Fotango Ltd. All Rights Reserved.
423  
424 This program is free software; you can redistribute
425 it and/or modify it under the same terms as Perl itself.
426  
427 =head1 BUGS
428  
429 Template::TAL creates superfluous XML namespace attributes in the
430 output.
431  
432 Please report any bugs you find via the CPAN RT system.
433 http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Template::TAL
434  
435 =head1 SEE ALSO
436  
437 The TAL specification: http://www.zope.org/Wikis/DevSite/Projects/ZPT/TAL%20Specification%201.4
438  
439 L<Petal>, another Perl implementation of TAL on CPAN.
440  
441 =cut
442  
443 1;