Declare/Tags.pm

filter: Statementstmt 97.1% 276 / 284 Branchbran 90.9% 80 / 88 Conditioncond 75.5% 37 / 49 MC/DCmcdc 53.3% 16 / 30 Subroutinesub 96.0% 49 / 51 Podpod 100% 18 / 18 totaltotal 91.5% 476 / 520 CC 66 SCAR 15.9
CC
66
Cov
93%
_tag
13.0
import
11.1
_show_template
7.0
CRAP 4.9
↑ Summary Declare.pm »
1 55 ▶use 5.006;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 55 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 48 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 #use Smart::Comments;
5 #use Smart::Comments '####';
6  
7 package Template::Declare::Tags;
8  
9 48 our $VERSION = '0.43';
10  
11 48 ▶use Template::Declare;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 48 ▶use base 'Exporter';
Subroutine BEGIN: called CC=1 SCAR=0.0
13 48 ▶use Carp qw(carp croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 48 ▶use Symbol 'qualify_to_ref';
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 48 our $self;
17  
18 48 our @EXPORT = qw(
19 template private current_template current_base_path
20 show show_page
21 attr with get_current_attr
22 outs outs_raw
23 xml_decl
24 under setting
25 smart_tag_wrapper create_wrapper
26 $self
27 );
28  
29 48 our @TAG_SUB_LIST;
30 48 our @TagSubs;
31 48 *TagSubs = \@TAG_SUB_LIST; # For backward compatibility only
32  
33 48 our %ATTRIBUTES = ();
34 48 our %ELEMENT_ID_CACHE = ();
35 48 our $TAG_NEST_DEPTH = 0;
36 48 our $TAG_INDENTATION = 1;
37 48 our $EOL = "\n";
38 48 our @TEMPLATE_STACK = ();
39  
40 48 our $SKIP_XML_ESCAPING = 0;
41  
42 105 ▶sub import {
Subroutine import: called CC=11 SCAR=24.1
43 105 my $self = shift;
44 105 my @set_modules;
45 105 ▶ if (!@_) {
Branch: 1 branch
BranchTrueFalseTotal
unless (@_) 90 15 105
46 90 push @_, 'HTML';
47 }
48 ### @_
49 ### caller: caller()
50  
51 # XXX We can't reset @TAG_SUB_LIST here since
52 # use statements always run at BEGIN time.
53 # A better approach may be install such lists
54 # directly into the caller's namespace...
55 #undef @TAG_SUB_LIST;
56  
57 105 ▶ while (@_) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_) 112 105 217
58 112 my $lang = shift;
59 112 my $opts;
60 112 ▶ if (ref $_[0] and ref $_[0] eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $_[0] and ref $_[0] eq "HASH") 7 105 112
Condition66%2/3
ref $_[0] and ref $_[0] eq "HASH"
!ll&&!rl&&r
10507
MC/DC50%1/2
ref $_[0] and ref $_[0] eq "HASH"
ref $_[0] ref $_[0] eq "HASH"
Truth table66%2/3
A and B
A= ref $_[0]B= ref $_[0] eq "HASH"
ABresult
0X0
100
111
61 7 $opts = shift;
62 7 ▶ $opts->{package} ||= $opts->{namespace};
Condition100%3/3
$opts->{"package"} ||= $opts->{"namespace"}
l!l&&r!l&&!r
151
MC/DC100%2/2
$opts->{"package"} ||= $opts->{"namespace"}
$opts->{"package"} $opts->{"namespace"}
Truth table100%3/3
A ||= B
A= $opts->{"package"}B= $opts->{"namespace"}
ABresult
1X1
011
000
63 # XXX TODO: carp if the derived package already exists?
64 }
65 112 ▶ $opts->{package} ||= scalar(caller);
Condition100%2/2
$opts->{"package"} ||= scalar caller
l!l
6106
MC/DC100%1/1
$opts->{"package"} ||= scalar caller
$opts->{"package"}
Truth table100%2/2
A
A= $opts->{"package"}
Aresult
11
00
66 my $module = $opts->{from} ||
67 112 ▶ "Template::Declare::TagSet::$lang";
Condition100%2/2
$opts->{'from'} || "Template::Declare::TagSet::$lang"
l!l
2110
MC/DC100%1/1
$opts->{'from'} || "Template::Declare::TagSet::$lang"
$opts->{'from'}
Truth table100%2/2
A
A= $opts->{'from'}
Aresult
11
00
68  
69 ### Loading tag set: $module
70 112 ▶ if (! $module->can('get_tag_list') ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($module->can("get_tag_list")) 54 58 112
71 47 ▶ eval "use $module";
Subroutine BEGIN: called CC=1 SCAR=0.0
72 54 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 54 54
73 0 warn $@;
74 0 croak "Failed to load tagset module $module";
75 }
76 }
77 ### TagSet options: $opts
78 112 my $tagset = $module->new($opts);
79 112 my $tag_list = $tagset->get_tag_list;
80 Template::Declare::Tags::install_tag($_, $tagset)
81 112 for @$tag_list;
82 }
83 105 __PACKAGE__->export_to_level(1, $self);
84 }
85  
86 16562 ▶sub _install {
Subroutine _install: called CC=3 SCAR=11.0
87 16562 my ($override, $package, $subname, $coderef) = @_;
88  
89 16562 my $name = $package . '::' . $subname;
90 16562 my $slot = qualify_to_ref($name);
91 16562 ▶ return if !$override and *$slot{CODE};
Branch: 1 branch
BranchTrueFalseTotal
if not $override and *$slot{"CODE"} 375 16187 16562
Condition100%2/2
not $override and *$slot{"CODE"}
!ll
15967595
MC/DC100%1/1
not $override and *$slot{"CODE"}
not $override
Truth table100%2/2
not(A)
A= not $override
Aresult
00
11
92  
93 48 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
94 16187 *$slot = $coderef;
95 }
96  
97 =head1 NAME
98  
99 Template::Declare::Tags - Build and install XML Tag subroutines for Template::Declare
100  
101 =head1 SYNOPSIS
102  
103 package MyApp::Templates;
104  
105 use base 'Template::Declare';
106 use Template::Declare::Tags 'HTML';
107  
108 template main => sub {
109 link {}
110 table {
111 row {
112 cell { "Hello, world!" }
113 }
114 }
115 img { attr { src => 'cat.gif' } }
116 img { src is 'dog.gif' }
117 };
118  
119 Produces:
120  
121 <link />
122 <table>
123 <tr>
124 <td>Hello, world!</td>
125 </tr>
126 </table>
127 <img src="cat.gif" />
128 <img src="dog.gif" />
129  
130 Using XUL templates with a namespace:
131  
132 package MyApp::Templates;
133  
134 use base 'Template::Declare';
135 use Template::Declare::Tags
136 'XUL', HTML => { namespace => 'html' };
137  
138 template main => sub {
139 groupbox {
140 caption { attr { label => 'Colors' } }
141 html::div { html::p { 'howdy!' } }
142 html::br {}
143 }
144 };
145  
146 Produces:
147  
148 <groupbox>
149 <caption label="Colors" />
150 <html:div>
151 <html:p>howdy!</html:p>
152 </html:div>
153 <html:br></html:br>
154 </groupbox>
155  
156 =head1 DESCRIPTION
157  
158 C<Template::Declare::Tags> is used to generate templates and install
159 subroutines for tag sets into the calling namespace.
160  
161 You can specify the tag sets to install by providing a list of tag modules in
162 the C<use> statement:
163  
164 use Template::Declare::Tags qw/ HTML XUL /;
165  
166 By default, Template::Declare::Tags uses the tag set provided by
167 L<Template::Declare::TagSet::HTML>. So
168  
169 use Template::Declare::Tags;
170  
171 is equivalent to
172  
173 use Template::Declare::Tags 'HTML';
174  
175 Currently L<Template::Declare> bundles the following tag sets:
176 L<Template::Declare::TagSet::HTML>, L<Template::Declare::TagSet::XUL>,
177 L<Template::Declare::TagSet::RDF>, and L<Template::Declare::TagSet::RDF::EM>.
178  
179 You can specify your own tag set classes, as long as they subclass
180 L<Template::Declare::TagSet> and implement the corresponding methods (e.g.
181 C<get_tag_list>).
182  
183 If you implement a custom tag set module named
184 C<Template::Declare::TagSet::Foo>, you can load it into a template module like
185 so:
186  
187 use Template::Declare::Tags 'Foo';
188  
189 If your tag set module is not under the
190 L<Template::Declare::TagSet|Template::Declare::TagSet> namespace, use the
191 C<from> option to load it. Fore example, if you created a tag set named
192 C<MyTag::Foo>, then you could load it like so:
193  
194 use Template::Declare::Tags Foo => { from => 'MyTag::Foo' };
195  
196 XML namespaces are emulated by Perl packages. For example, to embed HTML tags
197 within XUL using the C<html> namespace:
198  
199 package MyApp::Templates;
200  
201 use base 'Template::Declare';
202 use Template::Declare::Tags 'XUL', HTML => { namespace => 'html' };
203  
204 template main => sub {
205 groupbox {
206 caption { attr { label => 'Colors' } }
207 html::div { html::p { 'howdy!' } }
208 html::br {}
209 }
210 };
211  
212 This will output:
213  
214 <groupbox>
215 <caption label="Colors" />
216 <html:div>
217 <html:p>howdy!</html:p>
218 </html:div>
219 <html:br></html:br>
220 </groupbox>
221  
222 Behind the scenes, C<Template::Declare::Tags> generates a Perl package named
223 C<html> and installs the HTML tag subroutines into that package. On the other
224 hand, XUL tag subroutines are installed into the current package, namely,
225 C<MyApp::Templates> in the previous example.
226  
227 There may be cases when you want to specify a different Perl package for a
228 particular XML namespace. For instance, if the C<html> Perl package has
229 already been used for other purposes in your application and you don't want to
230 install subs there and mess things up, use the C<package> option to install
231 them elsewhere:
232  
233 package MyApp::Templates;
234 use base 'Template::Declare';
235 use Template::Declare::Tags 'XUL', HTML => {
236 namespace => 'htm',
237 package => 'MyHtml'
238 };
239  
240 template main => sub {
241 groupbox {
242 caption { attr { label => 'Colors' } }
243 MyHtml::div { MyHtml::p { 'howdy!' } }
244 MyHtml::br {}
245 }
246 };
247  
248 This code will generate something like the following:
249  
250 <groupbox>
251 <caption label="Colors" />
252 <htm:div>
253 <htm:p>howdy!</htm:p>
254 </htm:div>
255 <htm:br></htm:br>
256 </groupbox>
257  
258 =head1 METHODS AND SUBROUTINES
259  
260 =head2 Declaring templates
261  
262 =head3 template TEMPLATENAME => sub { 'Implementation' };
263  
264 template select_list => sub {
265 my $self = shift;
266 select {
267 option { $_ } for @_;
268 }
269 };
270  
271 Declares a template in the current package. The first argument to the template
272 subroutine will always be a C<Template::Declare> object. Subsequent arguments
273 will be all those passed to C<show()>. For example, to use the above example
274 to output a select list of colors, you'd call it like so:
275  
276 Template::Declare->show('select_list', qw(red yellow green purple));
277  
278 You can use any URL-legal characters in the template name;
279 C<Template::Declare> will encode the template as a Perl subroutine and stash
280 it where C<show()> can find it.
281  
282 (Did you know that you can have characters like ":" and "/" in your Perl
283 subroutine names? The easy way to get at them is with C<can>).
284  
285 =cut
286  
287 160 ▶sub template ($$) {
Subroutine template: called CC=2 SCAR=6.9
Pod documented
288 160 my $template_name = shift;
289 160 my $coderef = shift;
290 160 my $template_class = ( caller(0) )[0];
291  
292 48 ▶ no warnings qw( uninitialized redefine );
Subroutine BEGIN: called CC=1 SCAR=0.0
293  
294 # template "foo" ==> CallerPkg::_jifty_template_foo;
295 # template "foo/bar" ==> CallerPkg::_jifty_template_foo/bar;
296 214 ▶ my $codesub = sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
297 214 ▶ local $self = shift || $self || $template_class;
Condition66%4/6
shift() || $Template::Declare::Tags::self || $template_class
l!l&&r!l&&!r
521620
shift() or $Template::Declare::Tags::self
l!l&&r!l&&!r
520162
MC/DC0%0/3
shift() || $Template::Declare::Tags::self || $template_class
shift() $Template::Declare::Tags::self $template_class
Truth table50%2/4
A or B || C
A= shift()B= $Template::Declare::Tags::selfC= $template_class
ABCresult
1XX1
01X1
0011
0000
298 214 unshift @_, $self, $coderef;
299 214 goto $self->can('_dispatch_template');
300 160 };
301  
302 160 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 11 149 160
303 # We're being called by something like private that doesn't want us to register ourselves
304 11 return ( $template_class, $template_name, $codesub );
305 } else {
306 # We've been called in a void context and should register this template
307 149 Template::Declare::register_template(
308 $template_class,
309 $template_name,
310 $codesub,
311 );
312 }
313 }
314  
315 =head3 private template TEMPLATENAME => sub { 'Implementation' };
316  
317 private template select_list => sub {
318 my $self = shift;
319 select {
320 option { $_ } for @_;
321 }
322 };
323  
324 Declares that a template isn't available to be called directly from client
325 code. The resulting template can instead only be called from the package in
326 which it's created.
327  
328 =cut
329  
330 11 ▶sub private (@) {
Subroutine private: called CC=1 SCAR=0.0
Pod documented
331 11 my $class = shift;
332 11 my $subname = shift;
333 11 my $code = shift;
334 11 Template::Declare::register_private_template( $class, $subname, $code );
335 }
336  
337 =head2 Showing templates
338  
339 =head3 show [$template_name or $template_coderef], args
340  
341 show( main => { user => 'Bob' } );
342  
343 Displays templates. The first argument is the name of the template to be
344 displayed. Any additional arguments will be passed directly to the template.
345  
346 C<show> can either be called with a template name or a package/object and a
347 template. (It's both functional and OO.)
348  
349 If called from within a Template::Declare subclass, then private templates are
350 accessible and visible. If called from something that isn't a
351 Template::Declare, only public templates will be visible.
352  
353 From the outside world, users can either call C<< Template::Declare->show() >>,
354 C<< show() >> exported from Template::Declare::Tags or
355 C<Template::Declare::Tags::show()> directly to render a publicly visible template.
356  
357 Private templates may only be called from within the C<Template::Declare>
358 package.
359  
360 =cut
361  
362 119 ▶sub show {
Subroutine show: called CC=2 SCAR=6.9
Pod documented
363 119 my $template = shift;
364  
365 # if we're inside a template, we should show private templates
366 119 ▶ if ( caller->isa('Template::Declare') ) {
Branch: 1 branch
BranchTrueFalseTotal
if ((caller)->isa('Template::Declare')) { } 66 53 119
367 66 _show_template( $template, 1, \@_ );
368 66 return Template::Declare->buffer->data;
369 } else {
370 53 show_page( $template, @_);
371 }
372  
373 }
374  
375 =head3 show_page
376  
377 show_page( main => { user => 'Bob' } );
378  
379 Like C<show()>, but does not dispatch to private templates. It's used
380 internally by C<show()> when when that method is called from outside a
381 template class.
382  
383 =cut
384  
385 167 ▶sub show_page {
Subroutine show_page: called CC=1 SCAR=0.0
Pod documented
386 167 my $template = shift;
387 167 my $args = \@_;
388  
389 167 Template::Declare->buffer->push(
390 private => defined wantarray,
391 from => "T::D path $template",
392 );
393 167 _show_template( $template, 0, $args );
394 165 %ELEMENT_ID_CACHE = ();
395 165 return Template::Declare->buffer->pop;
396 }
397  
398 =head2 Attributes
399  
400 =head3 attr HASH
401  
402 attr { src => 'logo.png' };
403  
404 Specifies attributes for the element tag in which it appears. For example, to
405 add a class and ID to an HTML paragraph:
406  
407 p {
408 attr {
409 class => 'greeting text',
410 id => 'welcome',
411 };
412 'This is a welcoming paragraph';
413 }
414  
415 =cut
416  
417 52 ▶sub attr (&;@) {
Subroutine attr: called CC=2 SCAR=6.9
Pod documented
418 52 my $code = shift;
419 52 my @rv = $code->();
420 52 ▶ while ( my ( $field, $val ) = splice( @rv, 0, 2 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@rv, 0, 2)) 68 51 119
421  
422 # only defined whle in a tag context
423 68 append_attr( $field, $val );
424 }
425 51 return @_;
426 }
427  
428 =head3 ATTR is VALUE
429  
430 Attributes can also be specified by using C<is>, as in
431  
432 p {
433 class is 'greeting text';
434 id is 'welcome';
435 'This is a welcoming paragraph';
436 }
437  
438 A few tricks work for 'is':
439  
440 http_equiv is 'foo'; # => http-equiv="foo"
441 xml__lang is 'foo'; # => xml:lang="foo"
442  
443 So double underscore replaced with colon and single underscore with dash.
444  
445 =cut
446  
447 # 'is' is declared later, when needed, using 'local *is::AUTOLOAD = sub {};'
448  
449 =head3 with
450  
451 with ( id => 'greeting', class => 'foo' ),
452 p { 'Hello, World wide web' };
453  
454 An alternative way to specify attributes for a tag, just for variation. The
455 standard way to do the same as this example using C<attr> is:
456  
457 p { attr { id => 'greeting', class => 'foo' }
458 'Hello, World wide web' };
459  
460 =cut
461  
462 37 ▶sub with (@) {
Subroutine with: called CC=6 SCAR=17.9
Pod documented
463 37 %ATTRIBUTES = ();
464 37 ▶ while ( my ( $key, $val ) = splice( @_, 0, 2 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@_, 0, 2)) 44 36 80
465 48 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
466 44 $ATTRIBUTES{$key} = $val;
467  
468 44 ▶ if ( lc($key) eq 'id' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $key eq "id") 34 10 44
469 34 ▶ if ( $ELEMENT_ID_CACHE{$val}++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($Template::Declare::Tags::ELEMENT_ID_CACHE{$val}++) 11 23 34
470 11 my $msg = "HTML appears to contain illegal duplicate element id: $val";
471 11 ▶ die $msg if Template::Declare->strict;
Branch: 1 branch
BranchTrueFalseTotal
if "Template::Declare"->strict 1 10 11
472 10 warn $msg;
473 }
474 }
475  
476 }
477 36 ▶ wantarray ? () : '';
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 34 36
478 }
479  
480 =head2 Displaying text and raw data
481  
482 =head3 outs STUFF
483  
484 p { outs 'Grettings & welcome pyoonie hyoomon.' }
485  
486 HTML-encodes its arguments and appends them to C<Template::Declare>'s output
487 buffer. This is similar to simply returning a string from a tag function call,
488 but is occasionally useful when you need to output a mix of things, as in:
489  
490 p { outs 'hello'; em { 'world' } }
491  
492 =head3 outs_raw STUFF
493  
494 p { outs_raw "That's what <em>I'm</em> talking about!' }
495  
496 Appends its arguments to C<Template::Declare>'s output buffer without HTML
497 escaping.
498  
499 =cut
500  
501 82 ▶sub outs { _outs( 0, @_ ); }
Subroutine outs: called CC=1 SCAR=0.0
Pod documented
502 31 ▶sub outs_raw { _outs( 1, @_ ); }
Subroutine outs_raw: called CC=1 SCAR=0.0
Pod documented
503  
504 =head2 Installing tags and wrapping stuff
505  
506 =head3 install_tag TAGNAME, TAGSET
507  
508 install_tag video => 'Template::Declare::TagSet::HTML';
509  
510 Sets up TAGNAME as a tag that can be used in user templates. TAGSET is an
511 instance of a subclass for L<Template::Declare::TagSet>.
512  
513 =cut
514  
515 15967 ▶sub install_tag {
Subroutine install_tag: called CC=4 SCAR=13.9
Pod documented
516 15967 my $tag = $_[0]; # we should not do lc($tag) here :)
517 15967 my $name = $tag;
518 15967 my $tagset = $_[1];
519  
520 15967 my $alternative = $tagset->get_alternate_spelling($tag);
521 15967 ▶ if ( defined $alternative ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $alternative) 595 15372 15967
522 _install(
523 0, # do not override
524 scalar(caller), $tag,
525 1 ▶ sub (&) {
Subroutine __ANON__: called CC=1 SCAR=0.0
526 1 die "$tag {...} is invalid; use $alternative {...} instead.\n";
527 }
528 595 );
529 ### Exporting place-holder sub: $name
530 # XXX TODO: more checking here
531 595 ▶ if ($name !~ /^(?:base|tr|time)$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($name =~ /^(?:base|tr|time)$/) 203 392 595
532 203 push @EXPORT, $name;
533 203 push @TAG_SUB_LIST, $name;
534 }
535 595 ▶ $name = $alternative or return;
Branch: 1 branch
BranchTrueFalseTotal
$name = $alternative or return 595 0 595
536 }
537  
538 # We don't need this since we directly install
539 # subs into the target package.
540 #push @EXPORT, $name;
541 15967 push @TAG_SUB_LIST, $name;
542  
543 48 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
544 48 ▶ no warnings 'redefine';
Subroutine BEGIN: called CC=1 SCAR=0.0
545 #### Installing tag: $name
546 # XXX TODO: use sub _install to insert subs into the caller's package so as to support XML packages
547 422 ▶ my $code = sub (&;$) {
Subroutine __ANON__: called CC=3 SCAR=11.0
548 422 local *__ANON__ = $tag;
549 422 ▶ if ( defined wantarray and not wantarray ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray and not wantarray) { } 85 337 422
Condition100%3/3
defined wantarray and not wantarray
!ll&&!rl&&r
23010785
MC/DC100%2/2
defined wantarray and not wantarray
defined wantarray not wantarray
Truth table100%3/3
A and not(B)
A= defined wantarrayB= not wantarray
ABresult
0X0
100
111
550  
551 # Scalar context - return a coderef that represents ourselves.
552 85 my @__ = @_;
553 85 my $_self = $self;
554 85 ▶ my $sub = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
555 85 local $self = $_self;
556 85 local *__ANON__ = $tag;
557 85 _tag($tagset, $tag, @__);
558 85 };
559 85 bless $sub, 'Template::Declare::Tag';
560 85 return $sub;
561 } else {
562 337 _tag($tagset, $tag, @_);
563 }
564 15967 };
565 15967 _install(
566 1, # do override the existing sub with the same name
567 $tagset->package => $name => $code
568 );
569 }
570  
571 =head3 smart_tag_wrapper
572  
573 # create a tag that has access to the arguments set with L</with>.
574 sub sample_smart_tag (&) {
575 my $code = shift;
576  
577 smart_tag_wrapper {
578 my %args = @_; # set using 'with'
579 outs( 'keys: ' . join( ', ', sort keys %args) . "\n" );
580 $code->();
581 };
582 }
583  
584 # use it
585 with ( foo => 'bar', baz => 'bundy' ), sample_smart_tag {
586 outs( "Hello, World!\n" );
587 };
588  
589 The output would be
590  
591 keys: baz, foo
592 Hello, World!
593  
594 The smart tag wrapper allows you to create code that has access to the
595 attribute arguments specified via C<with>. It passes those arguments in to the
596 wrapped code in C<@_>. It also takes care of putting the output in the right
597 place and tidying up after itself. This might be useful to change the behavior
598 of a template based on attributes passed to C<with>.
599  
600 =cut
601  
602 5 ▶sub smart_tag_wrapper (&) {
Subroutine smart_tag_wrapper: called CC=4 SCAR=14.3
Pod documented
603 5 my $coderef = shift;
604  
605 5 Template::Declare->buffer->append($EOL);
606 5 Template::Declare->buffer->push( from => "T::D tag wrapper", private => 1 );
607  
608 5 my %attr = %ATTRIBUTES;
609 5 %ATTRIBUTES = (); # prevent leakage
610  
611 my $last = join '',
612 5 ▶ map { ref($_) ? $_ : _postprocess($_) }
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 0 5 5
613 $coderef->(%attr);
614  
615 5 my $content = Template::Declare->buffer->pop;
616 5 ▶ $content .= "$last" if not length $content and length $last;
Branch: 1 branch
BranchTrueFalseTotal
if not length $content and length $last 0 5 5
Condition33%1/3
not length $content and length $last
!ll&&!rl&&r
500
MC/DC0%0/2
not length $content and length $last
not length $content length $last
Truth table33%1/3
not(A) and B
A= not length $contentB= length $last
ABresult
0X0
100
111
617 5 Template::Declare->buffer->append( $content );
618  
619 5 return '';
620 }
621  
622 =head3 create_wrapper WRAPPERNAME => sub { 'Implementation' };
623  
624 create_wrapper basics => sub {
625 my $code = shift;
626 html {
627 head { title { 'Welcome' } };
628 body { $code->() }
629 }
630 };
631  
632 C<create_wrapper> declares a wrapper subroutine that can be called like a tag
633 sub, but can optionally take arguments to be passed to the wrapper sub. For
634 example, if you wanted to wrap all of the output of a template in the usual
635 HTML headers and footers, you can do something like this:
636  
637 package MyApp::Templates;
638 use Template::Declare::Tags;
639 use base 'Template::Declare';
640  
641 BEGIN {
642 create_wrapper wrap => sub {
643 my $code = shift;
644 my %params = @_;
645 html {
646 head { title { outs "Hello, $params{user}!"} };
647 body {
648 $code->();
649 div { outs 'This is the end, my friend' };
650 };
651 }
652 };
653 }
654  
655 template inner => sub {
656 wrap {
657 h1 { outs "Hello, Jesse, s'up?" };
658 } user => 'Jesse';
659 };
660  
661 Note how the C<wrap> wrapper function is available for calling after it has
662 been declared in a C<BEGIN> block. Also note how you can pass arguments to the
663 function after the closing brace (you don't need a comma there!).
664  
665 The output from the "inner" template will look something like this:
666  
667 <html>
668 <head>
669 <title>Hello, Jesse!</title>
670 </head>
671 <body>
672 <h1>Hello, Jesse, s&#39;up?</h1>
673 <div>This is the end, my friend</div>
674 </body>
675 </html>
676  
677 =cut
678  
679 1 ▶sub create_wrapper ($$) {
Subroutine create_wrapper: called CC=1 SCAR=0.0
Pod documented
680 1 my $wrapper_name = shift;
681 1 my $coderef = shift;
682 1 my $template_class = caller;
683  
684 # Shove the code ref into the calling class.
685 48 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
686 1 ▶ *{"$template_class\::$wrapper_name"} = sub (&;@) { goto $coderef };
Subroutine __ANON__: called CC=1 SCAR=0.0
687 }
688  
689 =head2 Helpers
690  
691 =head3 xml_decl HASH
692  
693 xml_decl { 'xml', version => '1.0' };
694  
695 Emits an XML declaration. For example:
696  
697 xml_decl { 'xml', version => '1.0' };
698 xml_decl { 'xml-stylesheet', href => "chrome://global/skin/", type => "text/css" };
699  
700 Produces:
701  
702 <?xml version="1.0"?>
703 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
704  
705 =cut
706  
707 4 ▶sub xml_decl (&;$) {
Subroutine xml_decl: called CC=2 SCAR=6.9
Pod documented
708 4 my $code = shift;
709 4 my @rv = $code->();
710 4 my $name = shift @rv;
711 4 outs_raw("<?$name");
712 4 ▶ while ( my ( $field, $val ) = splice( @rv, 0, 2 ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = splice(@rv, 0, 2)) 6 4 10
713 6 outs_raw(qq/ $field="$val"/);
714 }
715 4 outs_raw("?>$EOL");
716 4 return @_;
717 }
718  
719 =head3 current_template
720  
721 my $path = current_template();
722  
723 Returns the absolute path of the current template
724  
725 =cut
726  
727 217 ▶sub current_template {
Subroutine current_template: called CC=2 SCAR=6.9
Pod documented
728 217 ▶ return $TEMPLATE_STACK[-1] || '';
Condition100%2/2
$Template::Declare::Tags::TEMPLATE_STACK[-1] || ''
l!l
40177
MC/DC100%1/1
$Template::Declare::Tags::TEMPLATE_STACK[-1] || ''
$Template::Declare::Tags::TEMPLATE_STACK[-1]
Truth table100%2/2
A
A= $Template::Declare::Tags::TEMPLATE_STACK[-1]
Aresult
11
00
729 }
730  
731 =head3 current_base_path
732  
733 my $path = current_base_path();
734  
735 Returns the absolute base path of the current template
736  
737 =cut
738  
739 0 ▶sub current_base_path {
Subroutine current_base_path: not called CC=1 SCAR=6.9
Pod documented
740 # Rip it apart
741 0 my @parts = split('/', current_template());
742  
743 # Remove the last element
744 0 pop @parts;
745  
746 # Put it back together again
747 0 my $path = join('/', @parts);
748  
749 # And serve
750 0 return $path;
751 }
752  
753 =head3 under
754  
755 C<under> is a helper function providing semantic sugar for the C<mix> method
756 of L<Template::Declare|Template::Declare/"mix">.
757  
758 =cut
759  
760 37 ▶sub under ($) { return shift }
Subroutine under: called CC=1 SCAR=0.0
Pod documented
761  
762 =head3 setting
763  
764 C<setting> is a helper function providing semantic sugar for the C<mix> method
765 of L<Template::Declare|Template::Declare/"mix">.
766  
767 =cut
768  
769 2 ▶sub setting ($) { return shift }
Subroutine setting: called CC=1 SCAR=0.0
Pod documented
770  
771 =begin comment
772  
773 =head2 get_current_attr
774  
775 Deprecated.
776  
777 =end comment
778  
779 =cut
780  
781 0 ▶sub get_current_attr ($) {
Subroutine get_current_attr: not called CC=1 SCAR=6.9
Pod documented
782 0 $ATTRIBUTES{ $_[0] };
783 }
784  
785 422 ▶sub _tag {
Subroutine _tag: called CC=13 SCAR=25.7
786 422 my $tagset = shift;
787 422 my $tag = shift;
788 422 my $code = shift;
789 422 my $more_code = shift;
790 422 ▶ $tag = $tagset->namespace . ":$tag" if defined $tagset->namespace;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tagset->namespace 32 390 422
791  
792 Template::Declare->buffer->append(
793 $EOL
794 . ( " " x $TAG_NEST_DEPTH )
795 . "<$tag"
796 . join( '',
797 422 ▶ map { qq{ $_="} . ( $ATTRIBUTES{$_} || '' ) . qq{"} }
Condition50%1/2
$Template::Declare::Tags::ATTRIBUTES{$_} || ''
l!l
350
MC/DC0%0/1
$Template::Declare::Tags::ATTRIBUTES{$_} || ''
$Template::Declare::Tags::ATTRIBUTES{$_}
Truth table50%1/2
A
A= $Template::Declare::Tags::ATTRIBUTES{$_}
Aresult
11
00
798 sort keys %ATTRIBUTES )
799 );
800  
801 422 my $attrs = "";
802 422 my $last;
803 {
804 48 ▶ no warnings qw( uninitialized redefine once );
Subroutine BEGIN: called CC=1 SCAR=0.0
805  
806 26 ▶ local *is::AUTOLOAD = sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
807 26 shift;
808  
809 26 my $field = our $AUTOLOAD;
810 26 $field =~ s/.*:://;
811  
812 26 $field =~ s/__/:/g; # xml__lang is 'foo' ====> xml:lang="foo"
813 26 $field =~ s/_/-/g; # http_equiv is 'bar' ====> http-equiv="bar"
814  
815 # Squash empty values, but not '0' values
816 26 ▶ my $val = join ' ', grep { defined $_ && $_ ne '' } @_;
Condition33%1/3
defined $_ && $_ ne ''
!ll&&!rl&&r
0026
MC/DC0%0/2
defined $_ && $_ ne ''
defined $_ $_ ne ''
Truth table33%1/3
A && B
A= defined $_B= $_ ne ''
ABresult
0X0
100
111
817  
818 26 append_attr( $field, $val );
819 422 };
820  
821 93 ▶ local *append_attr = sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
822 93 my $field = shift;
823 93 my $val = shift;
824  
825 93 $attrs .= ' ' . $field . q{="} . _postprocess($val, 1) . q{"};
826 93 ▶ wantarray ? () : '';
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 11 82 93
827 422 };
828  
829 422 local $TAG_NEST_DEPTH = $TAG_NEST_DEPTH + $TAG_INDENTATION;
830 422 %ATTRIBUTES = ();
831 422 Template::Declare->buffer->push( private => 1, from => "T::D tag $tag" );
832 422 ▶ $last = join '', map { ref($_) && $_->isa('Template::Declare::Tag') ? $_ : _postprocess($_) } $code->();
Branch: 1 branch
BranchTrueFalseTotal
ref $_ && $_->isa('Template::Declare::Tag') ? : 2 355 357
Condition100%3/3
ref $_ and $_->isa("Template::Declare::Tag")
!ll&&!rl&&r
35412
MC/DC100%2/2
ref $_ and $_->isa("Template::Declare::Tag")
ref $_ $_->isa("Template::Declare::Tag")
Truth table100%3/3
A and B
A= ref $_B= $_->isa("Template::Declare::Tag")
ABresult
0X0
100
111
833 }
834 422 my $content = Template::Declare->buffer->pop;
835 422 ▶ $content .= "$last" if not length $content and length $last;
Branch: 1 branch
BranchTrueFalseTotal
if not length $content and length $last 154 268 422
Condition100%3/3
not length $content and length $last
!ll&&!rl&&r
19177154
MC/DC100%2/2
not length $content and length $last
not length $content length $last
Truth table100%3/3
not(A) and B
A= not length $contentB= length $last
ABresult
0X0
100
111
836 422 ▶ Template::Declare->buffer->append($attrs) if length $attrs;
Branch: 1 branch
BranchTrueFalseTotal
if length $attrs 68 354 422
837  
838 422 ▶ if (length $content) {
Branch: 2 branches
BranchTrueFalseTotal
if (length $content) { } 345 77 422
elsif ($tagset->can_combine_empty_tags($tag)) { } 37 40 77
839 345 Template::Declare->buffer->append(">$content");
840 345 ▶ Template::Declare->buffer->append( $EOL . ( " " x $TAG_NEST_DEPTH )) if $content =~ /\</;
Branch: 1 branch
BranchTrueFalseTotal
if $content =~ /\</ 133 212 345
841 345 Template::Declare->buffer->append("</$tag>");
842 } elsif ( $tagset->can_combine_empty_tags($tag) ) {
843 37 Template::Declare->buffer->append(" />");
844 } else {
845 # Otherwise we supply a closing tag.
846 40 Template::Declare->buffer->append("></$tag>");
847 }
848  
849 422 ▶ return ( ref($more_code) && $more_code->isa('CODE') )
Branch: 1 branch
BranchTrueFalseTotal
ref $more_code && $more_code->isa('CODE') ? : 79 343 422
Condition66%2/3
ref $more_code and $more_code->isa("CODE")
!ll&&!rl&&r
343079
MC/DC50%1/2
ref $more_code and $more_code->isa("CODE")
ref $more_code $more_code->isa("CODE")
Truth table66%2/3
A and B
A= ref $more_codeB= $more_code->isa("CODE")
ABresult
0X0
100
111
850 ? $more_code->()
851 : '';
852 }
853  
854 233 ▶sub _resolve_template_path {
Subroutine _resolve_template_path: called CC=6 SCAR=17.9
855 233 my $template = shift;
856  
857 233 my @parts;
858 233 ▶ if ( substr($template, 0, 1) ne '/' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (substr($template, 0, 1) ne "/") 217 16 233
859 # relative
860 217 @parts = split '/', current_template();
861 # Get rid of the parent's template name
862 217 pop @parts;
863 }
864  
865 233 foreach ( split '/', $template ) {
866 310 ▶ if ( $_ eq '..' ) {
Branch: 2 branches
BranchTrueFalseTotal
if ($_ eq '..') { } 3 307 310
elsif ($_ ne '.' and $_ ne '') { } 288 22 310
867 3 pop @parts;
868 }
869 # Get rid of "." and empty entries by the way
870 ▶ elsif ( $_ ne '.' && $_ ne '' ) {
Condition100%3/3
$_ ne "." and $_ ne ""
!ll&&!rl&&r
316288
MC/DC100%2/2
$_ ne "." and $_ ne ""
$_ ne "." $_ ne ""
Truth table100%3/3
A and B
A= $_ ne "."B= $_ ne ""
ABresult
0X0
100
111
871 288 push @parts, $_;
872 }
873 }
874  
875 233 return join '/', @parts;
876 }
877  
878 233 ▶sub _show_template {
Subroutine _show_template: called CC=7 SCAR=19.5
879 233 my $template = shift;
880 233 my $inside_template = shift;
881 233 my $args = shift;
882 233 $template = _resolve_template_path($template);
883 233 local @TEMPLATE_STACK = (@TEMPLATE_STACK, $template);
884  
885 233 ▶ my $callable =
Branch: 1 branch
BranchTrueFalseTotal
ref $template && $template->isa('Template::Declare::Tag') ? : 0 233 233
Condition33%1/3
ref $template and $template->isa("Template::Declare::Tag")
!ll&&!rl&&r
23300
MC/DC0%0/2
ref $template and $template->isa("Template::Declare::Tag")
ref $template $template->isa("Template::Declare::Tag")
Truth table33%1/3
A and B
A= ref $templateB= $template->isa("Template::Declare::Tag")
ABresult
0X0
100
111
886 ( ref($template) && $template->isa('Template::Declare::Tag') )
887 ? $template
888 : Template::Declare->resolve_template( $template, $inside_template );
889  
890 # If the template was not found let the user know.
891 233 ▶ unless ($callable) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($callable) 19 214 233
892 19 my $msg = "The template '$template' could not be found";
893 19 ▶ $msg .= " (it might be private)" if !$inside_template;
Branch: 1 branch
BranchTrueFalseTotal
unless $inside_template 18 1 19
894 19 ▶ croak $msg if Template::Declare->strict;
Branch: 1 branch
BranchTrueFalseTotal
if "Template::Declare"->strict 1 18 19
895 18 carp $msg;
896 18 return '';
897 }
898  
899 214 ▶ if (my $instrumentation = Template::Declare->around_template) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $instrumentation = 'Template::Declare'->around_template) { } 6 208 214
900 $instrumentation->(
901 6 ▶ sub { &$callable($self, @$args) },
Subroutine __ANON__: called CC=1 SCAR=0.0
902 6 $template,
903 $args,
904 $callable,
905 );
906 }
907 else {
908 208 &$callable($self, @$args);
909 }
910  
911 213 return;
912 }
913  
914 113 ▶sub _outs {
Subroutine _outs: called CC=5 SCAR=16.2
915 113 my $raw = shift;
916 113 my @phrases = (@_);
917  
918 113 ▶ Template::Declare->buffer->push(
Condition66%2/3
defined wantarray && !wantarray
!ll&&!rl&&r
45680
MC/DC0%0/2
defined wantarray && !wantarray
defined wantarray !wantarray
Truth table66%2/3
A && not(B)
A= defined wantarrayB= !wantarray
ABresult
0X0
100
111
919 private => (defined wantarray and not wantarray), from => "T::D outs"
920 );
921  
922 113 foreach my $item ( grep {defined} @phrases ) {
923 112 ▶ my $returned = ref($item) eq 'CODE'
Branch: 2 branches
BranchTrueFalseTotal
ref $item eq 'CODE' ? : 0 112 112
$raw ? : 31 81 112
924 ? $item->()
925 : $raw
926 ? $item
927 : _postprocess($item);
928 112 Template::Declare->buffer->append( $returned );
929 }
930 113 return Template::Declare->buffer->pop;
931 }
932  
933 534 ▶sub _postprocess {
Subroutine _postprocess: called CC=4 SCAR=13.9
934 534 my $val = shift;
935 534 my $skip_postprocess = shift;
936  
937 534 ▶ return $val unless defined $val;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $val 8 526 534
938  
939 # stringify in case $val is object with overloaded ""
940 526 $val = "$val";
941 526 ▶ if ( ! $SKIP_XML_ESCAPING ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($Template::Declare::Tags::SKIP_XML_ESCAPING) 526 0 526
942 48 ▶ no warnings 'uninitialized';
Subroutine BEGIN: called CC=1 SCAR=0.0
943 526 $val =~ s/&/&#38;/g;
944 526 $val =~ s/</&lt;/g;
945 526 $val =~ s/>/&gt;/g;
946 526 $val =~ s/\(/&#40;/g;
947 526 $val =~ s/\)/&#41;/g;
948 526 $val =~ s/"/&#34;/g;
949 526 $val =~ s/'/&#39;/g;
950 }
951 526 ▶ $val = Template::Declare->postprocessor->($val)
Branch: 1 branch
BranchTrueFalseTotal
unless $skip_postprocess 433 93 526
952 unless $skip_postprocess;
953  
954 526 return $val;
955 }
956  
957 =begin comment
958  
959 =head2 append_attr
960  
961 C<append_attr> is a helper function providing an interface for setting
962 attributes from within tags. But it's better to use C<attr> or C<is> to set
963 your attributes. Nohting to see here, really. Move along.
964  
965 =end comment
966  
967 =cut
968  
969 1 ▶sub append_attr {
Subroutine append_attr: called CC=1 SCAR=0.0
Pod documented
970 1 die "Subroutine attr failed: $_[0] => '$_[1]'\n\t".
971 "(Perhaps you're using an unknown tag in the outer container?)";
972 }
973  
974 =head1 VARIABLES
975  
976 =over 4
977  
978 =item C<@Template::Declare::Tags::EXPORT>
979  
980 Holds the names of the static subroutines exported by this class. Tag
981 subroutines generated by tag sets, however, are not included here.
982  
983 =item C<@Template::Declare::Tags::TAG_SUB_LIST>
984  
985 Contains the names of the tag subroutines generated from a tag set.
986  
987 Note that this array won't get cleared automatically before another
988 C<< use Template::Decalre::Tags >> statement.
989  
990 C<@Template::Declare::Tags::TagSubs> is aliased to this variable for
991 backward-compatibility.
992  
993 =item C<$Template::Declare::Tags::TAG_NEST_DEPTH>
994  
995 Controls the indentation of the XML tags in the final outputs. For example,
996 you can temporarily disable a tag's indentation by the following lines of
997 code:
998  
999 body {
1000 pre {
1001 local $Template::Declare::Tags::TAG_NEST_DEPTH = 0;
1002 script { attr { src => 'foo.js' } }
1003 }
1004 }
1005  
1006 It generates
1007  
1008 <body>
1009 <pre>
1010 <script src="foo.js"></script>
1011 </pre>
1012 </body>
1013  
1014 Note that now the C<script> tag has I<no> indentation and we've got what we
1015 want. ;)
1016  
1017 =item C<$Template::Declare::Tags::SKIP_XML_ESCAPING>
1018  
1019 Disables XML escape postprocessing entirely. Use at your own risk.
1020  
1021 =back
1022  
1023 =head1 SEE ALSO
1024  
1025 L<Template::Declare::TagSet::HTML>,
1026 L<Template::Declare::TagSet::XUL>, L<Template::Declare>.
1027  
1028 =head1 AUTHORS
1029  
1030 Jesse Vincent <jesse@bestpractical.com>
1031  
1032 Agent Zhang <agentzh@yahoo.cn>
1033  
1034 =head1 COPYRIGHT
1035  
1036 Copyright 2006-2009 Best Practical Solutions, LLC.
1037  
1038 =cut
1039  
1040 package Template::Declare::Tag;
1041  
1042 48 ▶use overload '""' => \&stringify;
Subroutine BEGIN: called CC=1 SCAR=0.0
1043  
1044 5 ▶sub stringify {
Subroutine stringify: called CC=2 SCAR=7.2
1045 5 my $self = shift;
1046  
1047 5 ▶ if ( defined wantarray ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined wantarray) { } 5 0 5
1048 5 Template::Declare->buffer->push( private => 1, from => "T::D stringify" );
1049 5 my $returned = $self->();
1050 5 return Template::Declare->buffer->pop . $returned;
1051 } else {
1052 0 return $self->();
1053 }
1054 }
1055  
1056 48 1;
↑ Summary Declare.pm »