blib/lib/Template/Declare.pm untested

filter: Statementstmt 0.0% 0 / 199 Branchbran 0.0% 0 / 42 Conditioncond 0.0% 0 / 28 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 41 Podpod 0.0% 0 / 30 totaltotal 0.0% 0 / 340 CC 20 SCAR 20.6
CC
20
Cov
0%
init
30.0
resolve_template
20.0
_has_template
12.0
CRAP 7.8
1 use 5.006;
2 use warnings;
3 use strict;
4  
5 package Template::Declare;
6 use Template::Declare::Buffer;
7 use Class::ISA;
8 use String::BufferStack;
9  
10 our $VERSION = "0.40_02";
11  
12 use base 'Class::Data::Inheritable';
13 __PACKAGE__->mk_classdata('dispatch_to');
14 __PACKAGE__->mk_classdata('postprocessor');
15 __PACKAGE__->mk_classdata('templates');
16 __PACKAGE__->mk_classdata('private_templates');
17 __PACKAGE__->mk_classdata('buffer');
18 __PACKAGE__->mk_classdata('imported_into');
19 __PACKAGE__->mk_classdata('around_template');
20  
21 __PACKAGE__->dispatch_to( [] );
22 __PACKAGE__->postprocessor( sub { return wantarray ? @_ : $_[0] } );
23 __PACKAGE__->templates( {} );
24 __PACKAGE__->private_templates( {} );
25 __PACKAGE__->buffer( String::BufferStack->new );
26 __PACKAGE__->around_template( undef );
27  
28 *String::BufferStack::data = sub {
29 my $ref = shift;
30 if (@_) {
31 warn "Template::Declare->buffer->data called with argument; this usage is deprecated";
32 ${$ref->buffer_ref} = join("", @_);
33 }
34 return $ref->buffer;
35 };
36  
37 our $TEMPLATE_VARS;
38  
39 =head1 NAME
40  
41 Template::Declare - Perlish declarative templates
42  
43 =head1 SYNOPSIS
44  
45 Here's an example of basic HTML usage:
46  
47 package MyApp::Templates;
48 use Template::Declare::Tags; # defaults to 'HTML'
49 use base 'Template::Declare';
50  
51 template simple => sub {
52 html {
53 head {}
54 body {
55 p { 'Hello, world wide web!' }
56 }
57 }
58 };
59  
60 package main;
61 use Template::Declare;
62 Template::Declare->init( dispatch_to => ['MyApp::Templates'] );
63 print Template::Declare->show( 'simple' );
64  
65 And here's the output:
66  
67 <html>
68 <head></head>
69 <body>
70 <p>Hello, world wide web!
71 </p>
72 </body>
73 </html>
74  
75 =head1 DESCRIPTION
76  
77 C<Template::Declare> is a pure-Perl declarative HTML/XUL/RDF/XML templating
78 system.
79  
80 Yes. Another one. There are many others like it, but this one is ours.
81  
82 A few key features and buzzwords:
83  
84 =over
85  
86 =item *
87  
88 All templates are 100% pure Perl code
89  
90 =item *
91  
92 Simple declarative syntax
93  
94 =item *
95  
96 No angle brackets
97  
98 =item *
99  
100 "Native" XML namespace and declaration support
101  
102 =item *
103  
104 Mixins
105  
106 =item *
107  
108 Inheritance
109  
110 =item *
111  
112 Delegation
113  
114 =item *
115  
116 Public and private templates
117  
118 =back
119  
120 =head1 GLOSSARY
121  
122 =over
123  
124 =item template class
125  
126 A subclass of Template::Declare in which one or more templates are defined
127 using the C<template> keyword, or that inherits templates from a super class.
128  
129 =item template
130  
131 Created with the C<template> keyword, a template is a subroutine that uses
132 C<tags> to generate output.
133  
134 =item attribute
135  
136 An XML element attribute. For example, in C<< <img src="foo.png" /> >>, C<src>
137 is an attribute of the C<img> element.
138  
139 =item tag
140  
141 A subroutine that generates XML element-style output. Tag subroutines execute
142 blocks that generate the output, and can call other tags to generate a
143 properly hierarchical structure.
144  
145 =item tag set
146  
147 A collection of related tags defined in a subclass of
148 L<Template::Declare::TagSet> for a particular purpose, and which can be
149 imported into a template class. For example,
150 L<Template::Declare::TagSet::HTML> defines tags for emitting HTML elements.
151  
152 =item wrapper
153  
154 A subroutine that wraps the output from a template. Useful for wrapping
155 template output in common headers and footers, for example.
156  
157 =item dispatch class
158  
159 A template class that has been passed to L<C<init()>|/init> via the
160 C<dispatch_to> parameter. When L<show|/"show TEMPLATE"> is called, only
161 templates defined in or mixed into the dispatch classes will be executed.
162  
163 =item path
164  
165 The name specified for a template when it is created by the C<template>
166 keyword, or when a template is mixed into a template class.
167  
168 =item mixin
169  
170 A template mixed into a template class via L</mix>. Mixed-in templates may be
171 mixed in under prefix paths to distinguish them from the templates defined in
172 the dispatch classes.
173  
174 =item alias
175  
176 A template aliased into a template class via L</alias>. Aliased templates may
177 be added under prefix paths to distinguish them from the templates defined in
178 the dispatch classes.
179  
180 =item package variable
181  
182 Variables defined when mixing templates into a template class. These variables
183 are available only to the mixed-in templates; they are not even accessible
184 from the template class in which the templates were defined.
185  
186 =item helper
187  
188 A subroutine used in templates to assist in the generation of output, or in
189 template classes to assist in the mixing-in of templates. Output helpers
190 include C<outs()> for rending text output and C<xml_decl()> for rendering XML
191 declarations. Mixin helpers include C<into> for specifying a template class to
192 mix into, and C<under> for specifying a path prefix under which to mix
193 templates.
194  
195 =back
196  
197 =head1 Basics
198  
199 Like other Perl templating systems, there are two parts to Template::Declare:
200 the templates and the code that loads and executes the templates. Unlike other
201 template systems, the templates are written in Perl classes. A simple HTML
202 example is in the L</SYNOPSIS>.
203  
204 =head2 A slightly more advanced example
205  
206 In this example, we'll show off how to set attributes on HTML tags, how to
207 call other templates, and how to declare a I<private> template that can't be
208 called directly. We'll also show passing arguments to templates. First, the
209 template class:
210  
211 package MyApp::Templates;
212 use base 'Template::Declare';
213 use Template::Declare::Tags;
214  
215 private template 'util/header' => sub {
216 head {
217 title { 'This is a webpage' };
218 meta {
219 attr { generator => "This is not your father's frontpage" }
220 }
221 }
222 };
223  
224 private template 'util/footer' => sub {
225 my $self = shift;
226 my $time = shift || gmtime;
227  
228 div {
229 attr { id => "footer"};
230 "Page last generated at $time."
231 }
232 };
233  
234 template simple => sub {
235 my $self = shift;
236 my $user = shift || 'world wide web';
237  
238 html {
239 show('util/header');
240 body {
241 img { src is 'hello.jpg' }
242 p {
243 attr { class => 'greeting'};
244 "Hello, $user!"
245 };
246 };
247 show('util/footer', 'noon');
248 }
249 };
250  
251 A few notes on this example:
252  
253 =over
254  
255 =item *
256  
257 Since no parameter was passed to C<use Template::Declare::Tags>, the HTML tags
258 are imported by default.
259  
260 =item *
261  
262 The C<private> keyword indicates that a template is private. That means that
263 it can only be executed by other templates within the template class in which
264 it's declared. By default, C<< Template::Declare->show >> will not dispatch to
265 it.
266  
267 =item *
268  
269 The two private templates have longer paths than we've seen before:
270 C<util/header> and C<util/footer>. They must of course be called by their full
271 path names. You can put any characters you like into template names, but the
272 use of Unix filesystem-style paths is the most common (following on the
273 example of L<HTML::Mason|HTML::Mason>).
274  
275 =item *
276  
277 The first argument to a template is a class name. This can be useful for
278 calling methods defined in the class.
279  
280 =item *
281  
282 The C<show> sub executes another template. In this example, the C<simple>
283 template calls C<show('util/header')> and C<show('util/footer')> in order to
284 execute those private templates in the appropriate places.
285  
286 =item *
287  
288 Additional arguments to C<show> are passed on to the template being executed.
289 here, C<show('util/footer', 'noon')> is passing "noon" to the C<util/footer>
290 template, with the result that the "last generated at" string will display
291 "noon" instead of the default C<gmtime>.
292  
293 =item *
294  
295 In the same way, note that the C<simple> template expects an additional
296 argument, a user name.
297  
298 =item *
299  
300 In addition to using C<attr> to declare attributes for an element, you can
301 use C<is>, as in
302  
303 img { src is 'hello.jpg' }
304  
305 =back
306  
307 Now for executing the template:
308  
309 package main;
310 use Template::Declare;
311 Template::Declare->init( dispatch_to => ['MyApp::Templates'] );
312 print Template::Declare->show( '/simple', 'TD user');
313  
314 We've told Template::Declare to dispatch to templates defined in our template
315 class. And note how an additional argument is passed to C<show()>; that
316 argument, "TD user", will be passed to the C<simple> template, where it will
317 be used in the C<$user> variable.
318  
319 The output looks like this:
320  
321 <html>
322 <head>
323 <title>This is a webpage</title>
324 <meta generator="This is not your father&#39;s frontpage" />
325 </head>
326 <body>
327 <img src="hello.jpg" />
328 <p class="greeting">Hello, TD user!</p>
329 </body>
330 <div id="footer">Page last generated at Thu Sep 3 20:56:14 2009.</div>
331 </html>
332  
333 Note that the single quote in C<father's> was quoted for you. We sanitize
334 your output for you to help prevent cross-site scripting attacks.
335  
336 =head2 XUL
337  
338 Template::Declare isn't limited to just HTML. Let's do XUL!
339  
340 package MyApp::Templates;
341 use base 'Template::Declare';
342 use Template::Declare::Tags 'XUL';
343  
344 template main => sub {
345 xml_decl { 'xml', version => '1.0' };
346 xml_decl {
347 'xml-stylesheet',
348 href => "chrome://global/skin/",
349 type => "text/css"
350 };
351 groupbox {
352 caption { attr { label => 'Colors' } }
353 radiogroup {
354 for my $id ( qw< orange violet yellow > ) {
355 radio {
356 attr {
357 id => $id,
358 label => ucfirst($id),
359 $id eq 'violet' ? (selected => 'true') : ()
360 }
361 }
362 } # for
363 }
364 }
365 };
366  
367 The first thing to do in a template class is to subclass Template::Declare
368 itself. This is required so that Template::Declare always knows that it's
369 dealing with templates. The second thing is to C<use Template::Declare::Tags>
370 to import the set of tag subroutines you need to generate the output you want.
371 In this case, we've imported tags to support the creation of XUL. Other tag
372 sets include HTML (the default), and RDF.
373  
374 Templates are created using the C<template> keyword:
375  
376 template main => sub { ... };
377  
378 The first argument is the name of the template, also known as its I<path>. In
379 this case, the template's path is C<main> (or C</main>, both are allowed (to
380 keep both PHP and L<HTML::Mason> fans happy). The second argument is an
381 anonymous subroutine that uses the tag subs (and any other necessary code) to
382 generate the output for the template.
383  
384 The tag subs imported into your class take blocks as arguments, while a
385 number of helper subs take other arguments. For example, the C<xml_decl>
386 helper takes as its first argument the name of the XML declaration to be
387 output, and then a hash of the attributes of that declaration:
388  
389 xml_decl { 'xml', version => '1.0' };
390  
391 Tag subs are used by simply passing a block to them that generates the output.
392 Said block may of course execute other tag subs in order to represent the
393 hierarchy required in your output. Here, the C<radiogroup> tag calls the
394 C<radio> tag for each of three different colors:
395  
396 radiogroup {
397 for my $id ( qw< orange violet yellow > ) {
398 radio {
399 attr {
400 id => $id,
401 label => ucfirst($id),
402 $id eq 'violet' ? (selected => 'true') : ()
403 }
404 }
405 } # for
406 }
407  
408 Note the C<attr> sub. This helper function is used to add attributes to the
409 element created by the tag in which they appear. In the previous example, the
410 the C<id>, C<label>, and C<selected> attributes are added to each C<radio>
411 output.
412  
413 Once you've written your templates, you'll want to execute them. You do so by
414 telling Template::Declare what template classes to dispatch to and then asking
415 it to show you the output from a template:
416  
417 package main;
418 Template::Declare->init( dispatch_to => ['MyApp::Templates'] );
419 print Template::Declare->show( 'main' );
420  
421 The path passed to C<show> can be either C<main> or </main>, as you prefer. In
422 either event, the output would look like this:
423  
424 <?xml version="1.0"?>
425 <?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
426  
427 <groupbox>
428 <caption label="Colors" />
429 <radiogroup>
430 <radio id="orange" label="Orange" />
431 <radio id="violet" label="Violet" selected="true" />
432 <radio id="yellow" label="Yellow" />
433 </radiogroup>
434 </groupbox>
435  
436 =head2 Postprocessing
437  
438 Sometimes you just want simple syntax for inline elements. The following shows
439 how to use a postprocessor to emphasize text _like this_.
440  
441 package MyApp::Templates;
442 use Template::Declare::Tags;
443 use base 'Template::Declare';
444  
445 template before => sub {
446 h1 {
447 outs "Welcome to ";
448 em { "my" };
449 outs " site. It's ";
450 em { "great" };
451 outs "!";
452 };
453 };
454  
455 template after => sub {
456 h1 { "Welcome to _my_ site. It's _great_!" };
457 h2 { outs_raw "This is _not_ emphasized." };
458 img { src is '/foo/_bar_baz.png' };
459 };
460  
461 Here we've defined two templates in our template class, with the paths
462 C<before> and C<after>. The one new thing to note is the use of the C<outs>
463 and C<outs_raw> subs. C<outs> XML-encodes its argument and outputs it. You can
464 also just specify a string to be output within a tag call, but if you need to
465 mix tags and plain text within a tag call, as in the C<before> template here,
466 you'll need to use C<outs> to get things to output as you would expect.
467 C<outs_raw> is the same, except that it does no XML encoding.
468  
469 Now let's have a look at how we use these templates with a post-processor:
470  
471 package main;
472 use Template::Declare;
473 Template::Declare->init(
474 dispatch_to => ['MyApp::Templates'],
475 postprocessor => \&emphasize,
476 );
477  
478 print Template::Declare->show( 'before' );
479 print Template::Declare->show( 'after' );
480  
481 sub emphasize {
482 my $text = shift;
483 $text =~ s{_(.+?)_}{<em>$1</em>}g;
484 return $text;
485 }
486  
487 As usual, we've told Template::Declare to dispatch to our template class. A
488 new parameter to C<init()> is C<postprocessor>, which is a code reference that
489 should expect the template output as an argument. It can then transform that
490 text however it sees fit before returning it for final output. In this
491 example, the C<emphasize> subroutine looks for text that's emphasized using
492 _underscores_ and turns them into C<< <em>emphasis</em> >> HTML elements.
493  
494 We then execute both the C<before> and the C<after> templates with the output
495 ending up as:
496  
497 <h1>Welcome to
498 <em>my</em> site. It&#39;s
499 <em>great</em>!</h1>
500 <h1>Welcome to <em>my</em> site. It&#39;s <em>great</em>!</h1>
501 <h2>This is _not_ emphasized.</h2>
502 <img src="/foo/_bar_baz.png" />
503  
504 The thing to note here is that text passed to C<outs_raw> is not passed
505 through the postprocessor, and neither are attribute values (like the C<img>'s
506 C<src>).
507  
508 =head2 Inheritance
509  
510 Templates are really just methods. You can subclass your template packages to
511 override some of those methods:
512  
513 package MyApp::Templates::GenericItem;
514 use Template::Declare::Tags;
515 use base 'Template::Declare';
516  
517 template 'list' => sub {
518 my ($self, @items) = @_;
519 div {
520 show('item', $_) for @items;
521 }
522 };
523 template 'item' => sub {
524 my ($self, $item) = @_;
525 span { $item }
526 };
527  
528 package MyApp::Templates::BlogPost;
529 use Template::Declare::Tags;
530 use base 'MyApp::Templates::GenericItem';
531  
532 template 'item' => sub {
533 my ($self, $post) = @_;
534 h1 { $post->title }
535 div { $post->body }
536 };
537  
538 Here we have two template classes; the second, C<MyApp::Templates::BlogPost>,
539 inherits from the first, C<MyApp::Templates::GeniricItem>. Note also that
540 C<MyApp::Templates::BlogPost> overrides the C<item> template. So execute these
541 templates:
542  
543 package main;
544 use Template::Declare;
545  
546 Template::Declare->init( dispatch_to => ['MyApp::Templates::GenericItem'] );
547 print Template::Declare->show( 'list', 'foo', 'bar', 'baz' );
548  
549 Template::Declare->init( dispatch_to => ['MyApp::Templates::BlogPost'] );
550 my $post = My::Post->new(title => 'Hello', body => 'first post');
551 print Template::Declare->show( 'item', $post );
552  
553 First we execute the C<list> template in the base class, passing in some
554 items, and then we re-C<init()> Template::Declare and execute I<its> C<list>
555 template with an appropriate argument. Here's the output:
556  
557 <div>
558 <span>foo</span>
559 <span>bar</span>
560 <span>baz</span>
561 </div>
562  
563 <h1>Hello</h1>
564 <div>first post</div>
565  
566 So the override of the C<list> template in the subclass works as expected. For
567 another example, see L<Jifty::View::Declare::CRUD>.
568  
569 =head2 Wrappers
570  
571 There are two levels of wrappers in Template::Declare: template wrappers and
572 smart tag wrappers.
573  
574 =head3 Template Wrappers
575  
576 C<create_wrapper> declares a wrapper subroutine that can be called like a tag
577 sub, but can optionally take arguments to be passed to the wrapper sub. For
578 example, if you wanted to wrap all of the output of a template in the usual
579 HTML headers and footers, you can do something like this:
580  
581 package MyApp::Templates;
582 use Template::Declare::Tags;
583 use base 'Template::Declare';
584  
585 BEGIN {
586 create_wrapper wrap => sub {
587 my $code = shift;
588 my %params = @_;
589 html {
590 head { title { outs "Hello, $params{user}!"} };
591 body {
592 $code->();
593 div { outs 'This is the end, my friend' };
594 };
595 }
596 };
597 }
598  
599 template inner => sub {
600 wrap {
601 h1 { outs "Hello, Jesse, s'up?" };
602 } user => 'Jesse';
603 };
604  
605 Note how the C<wrap> wrapper function is available for calling after it has
606 been declared in a C<BEGIN> block. Also note how you can pass arguments to the
607 function after the closing brace (you don't need a comma there!).
608  
609 The output from the "inner" template will look something like this:
610  
611 <html>
612 <head>
613 <title>Hello, Jesse!</title>
614 </head>
615 <body>
616 <h1>Hello, Jesse, s&#39;up?</h1>
617 <div>This is the end, my friend</div>
618 </body>
619 </html>
620  
621 =head3 Tag Wrappers
622  
623 Tag wrappers are similar to template wrappers, but mainly function as syntax
624 sugar for creating subroutines that behave just like tags but are allowed to
625 contain arbitrary Perl code and to dispatch to other tag. To create one,
626 simply create a named subroutine with the prototype C<(&)> so that its
627 interface is the same as tags. Within it, use
628 L<C<smart_tag_wrapper>|Template::Declare::Tags/"smart_tag_wrapper"> to do the
629 actual execution, like so:
630  
631 package My::Template;
632 use Template::Declare::Tags;
633 use base 'Template::Declare';
634  
635 sub myform (&) {
636 my $code = shift;
637  
638 smart_tag_wrapper {
639 my %params = @_; # set using 'with'
640 form {
641 attr { %{ $params{attr} } };
642 $code->();
643 input { attr { type => 'submit', value => $params{value} } };
644 };
645 };
646 }
647  
648 template edit_prefs => sub {
649 with(
650 attr => { id => 'edit_prefs', action => 'edit.html' },
651 value => 'Save'
652 ), myform {
653 label { 'Time Zone' };
654 input { type is 'text'; name is 'tz' };
655 };
656 };
657  
658 Note in the C<edit_prefs> template that we've used
659 L<C<with>|Template::Declare::Tags/"with"> to set up parameters to be passed to
660 the smart wrapper. C<smart_tag_wrapper()> is the device that allows you to
661 receive those parameters, and also handles the magic of making sure that the
662 tags you execute within it are properly output. Here we've used C<myform>
663 similarly to C<form>, only C<myform> does something different with the
664 C<with()> arguments and outputs a submit element.
665  
666 Executing this template:
667  
668 Template::Declare->init( dispatch_to => ['My::Template'] );
669 print Template::Declare->show('edit_prefs');
670  
671 Yields this output:
672  
673 <form action="edit.html" id="edit_prefs">
674 <label>Time Zone</label>
675 <input type="text" name="tz" />
676 <input type="submit" value="Save" />
677 </form>
678  
679 =head2 Class Search Dispatching
680  
681 The classes passed via the C<dispatch_to> parameter to C<init()> specify all
682 of the templates that can be executed by subsequent calls to C<show()>.
683 Template searches through these classes in order to find those templates. Thus
684 it can be useful, when you're creating your template classes and determining
685 which to use for particular class to C<show()>, to have templates that
686 override other templates. This is similar to how an operating system will
687 search all the paths in the C<$PATH> environment variable for a program to
688 run, and to L<HTML::Mason> component roots or L<Template::Toolkit>'s
689 C<INCLUDE_PATH> parameter.
690  
691 For example, say you have this template class that defines a template that
692 you'll use for displaying images on your Web site.
693  
694 package MyApp::UI::Standard;
695 use Template::Declare::Tags;
696 use base 'Template::Declare';
697  
698 template image => sub {
699 my ($self, $src, $title) = @_;
700 img {
701 src is $src;
702 title is $title;
703 };
704 };
705  
706 As usual, you can use it like so:
707  
708 my @template_classes = 'MyApp::UI::Standard';
709 Template::Declare->init( dispatch_to => \@template_classes );
710 print Template::Declare->show('image', 'foo.png', 'Foo');
711  
712 We're explicitly using a reference to C<@template_classes> so that we can
713 manage this list ourselves.
714  
715 The output of this will be:
716  
717 <div class="std">
718 <img src="foo.png" title="Foo" />
719 <p class="caption"></p>
720 </div>
721  
722 But say that in some sections of your site you need to have a more formal
723 treatment of your photos. Maybe you publish photos from a wire service and
724 need to provide an appropriate credit. You might write the template class like
725 so:
726  
727 package MyApp::UI::Formal;
728 use Template::Declare::Tags;
729 use base 'Template::Declare';
730  
731 template image => sub {
732 my ($self, $src, $title, $credit, $caption) = @_;
733 div {
734 class is 'formal';
735 img {
736 src is $src;
737 title is $title;
738 };
739 p {
740 class is 'credit';
741 outs "Photo by $credit";
742 };
743 p {
744 class is 'caption';
745 outs $caption;
746 };
747 };
748 };
749  
750  
751 This, too, will work as expected, but the useful bit that comes in when you're
752 mixing and matching template classes to pass to C<dispatch_to> before
753 rendering a page. Maybe you always pass have MyApp::UI::Standard to
754 C<dispatch_to> because it has all of your standard formatting templates.
755 But when the code realizes that a particular page needs the more formal
756 treatment, you can prepend the formal class to the list:
757  
758 unshift @template_classes, 'MyApp::UI::Formal';
759 print Template::Declare->show(
760 'image',
761 'ap.png',
762 'AP Photo',
763 'Clark Kent',
764 'Big news'
765 );
766 shift @template_classes;
767  
768 In this way, made the formal C<image> template will be found first, yielding
769 this output:
770  
771 <div class="formal">
772 <img src="ap.png" title="AP Photo" />
773 <p class="credit">Photo by Clark Kent</p>
774 <p class="caption">Big news</p>
775 </div>
776  
777 At the end, we've shifted the formal template class off the C<dispatch_to>
778 list in order to restore the template classes the default configuration, ready
779 for the next request.
780  
781 =head2 Template Composition
782  
783 There are two methods of template composition: mixins and delegation. Their
784 interfaces are very similar, the only difference being the template invocant.
785  
786 =head2 Mixins
787  
788 Let's start with a mixin.
789  
790 package MyApp::UtilTemplates;
791 use Template::Declare::Tags;
792 use base 'Template::Declare';
793  
794 template content => sub {
795 my $self = shift;
796 my @paras = @_;
797 h1 { $self->get_title };
798 div {
799 id is 'content';
800 p { $_ } for @paras;
801 };
802 };
803  
804 package MyApp::Templates;
805 use Template::Declare::Tags;
806 use base 'Template::Declare';
807 mix MyApp::UtilTemplates under '/util';
808  
809 sub get_title { 'Kashmir' }
810  
811 template story => sub {
812 my $self = shift;
813 html {
814 head {
815 title { "My Site: " . $self->get_title };
816 };
817 body {
818 show( 'util/content' => 'first paragraph', 'second paragraph' );
819 };
820 };
821 };
822  
823 The first template class, C<MyApp::UtilTemplates>, defines a utility template,
824 called C<content>, for outputting the contents of page. Note its call to
825 C<< $self->get_title >> even though it doesn't have a C<get_title> method. This
826 is part of the mixin's "contract": it requires that the class it's mixed into
827 have a C<get_title()> method.
828  
829 The second template class, C<MyApp::Templates>, mixes C<MyApp::UtilTemplates>
830 into itself under the path C</util> and defines a C<get_title()> method as
831 required by the mixin. Then, its C<story> template calls the mixed-in template
832 as C<util/content>, because the C<content> template was mixed into the current
833 template under C</util>. Get it?
834  
835 Now we can use the usual template invocation:
836  
837 package main;
838 Template::Declare->init( dispatch_to => ['MyApp::Templates'] );
839 print Template::Declare->show('story');
840  
841 To appreciate our output:
842  
843 <html>
844 <head>
845 <title>My Site: Kashmir</title>
846 </head>
847 <body>
848 <h1>Kashmir</h1>
849 <div id="content">
850 <p>fist paragraph</p>
851 <p>second paragraph</p>
852 </div>
853 </body>
854 </html>
855  
856 Mixins are a very useful tool for template authors to add reusable
857 functionality to their template classes. But it's important to pay attention to
858 the mixin contracts so that you're sure to implement the required API in your
859 template class (here, the C<get_title()> method).
860  
861 =head3 Aliases
862  
863 Aliases are very similar to mixins, but implement delegation as a composition
864 pattern, rather than mixins. The upshot is that there is no contract provided
865 by an aliased class: it just works. This is because the invocant is the class
866 from which the aliases are imported, and therefore it will dispatch to methods
867 defined in the aliased class.
868  
869 For example, say that you wanted to output a sidebar on pages that need one
870 (perhaps your CMS has sidebar things). We can define a template class that
871 has a template for that:
872  
873 package MyApp::UI::Stuff;
874 use Template::Declare::Tags;
875 use base 'Template::Declare';
876  
877 sub img_path { '/ui/css' }
878  
879 template sidebar => sub {
880 my ($self, $thing) = @_;
881 div {
882 class is 'sidebar';
883 img { src is $self->img_path . '/sidebar.png' };
884 p { $_->content } for $thing->get_things;
885 };
886 };
887  
888 Note the use of the C<img_path()> method defined in the template class and
889 used by the C<sidebar> template. Now let's use it:
890  
891 package MyApp::Render;
892 use Template::Declare::Tags;
893 use base 'Template::Declare';
894 alias MyApp::UI::Stuff under '/stuff';
895  
896 template page => sub {
897 my ($self, $page) = @_;
898 h1 { $page->title };
899 for my $thing ($page->get_things) {
900 if ($thing->is('paragraph')) {
901 p { $thing->content };
902 } elsif ($thing->is('sidebar')) {
903 show( '/stuff/sidebar' => $thing );
904 }
905 }
906 };
907  
908 Here our rendering template class has aliased C<MyApp::UI::Stuff> under
909 C</stuff>. So the C<page> template calls C<show('/stuff/sidebar')> to invoke
910 the sidebar template. If we run this:
911  
912 Template::Declare->init( dispatch_to => ['MyApp::Render'] );
913 print Template::Declare->show( page => $page );
914  
915 We get output as you might expect:
916  
917 <h1>My page title</h1>
918 <p>Page paragraph</p>
919 <div class="sidebar">
920 <img src="/ui/css/sidebar.png" />
921 <p>Sidebar paragraph</p>
922 <p>Another paragraph</p>
923 </div>
924  
925 Now, let's say that you have political stuff that you want to use a different
926 image for in the sidebar. If that's the only difference, we can subclass
927 C<MyApp::UI::Stuff> and just override the C<img_path()> method:
928  
929 package MyApp::UI::Stuff::Politics;
930 use Template::Declare::Tags;
931 use base 'MyApp::UI::Stuff';
932  
933 sub img_path { '/politics/ui/css' }
934  
935 Now let's mix that into a politics template class:
936  
937 package MyApp::Render::Politics;
938 use Template::Declare::Tags;
939 use base 'Template::Declare';
940 alias MyApp::UI::Stuff::Politics under '/politics';
941  
942 template page => sub {
943 my ($self, $page) = @_;
944 h1 { $page->title };
945 for my $thing ($page->get_things) {
946 if ($thing->is('paragraph')) {
947 p { $thing->content };
948 } elsif ($thing->is('sidebar')) {
949 show( '/politics/sidebar' => $thing );
950 }
951 }
952 };
953  
954 The only difference between this template class and C<MyApp::Render> is that
955 it aliases C<MyApp::UI::Stuff::Politics> under C</politics>, and then calls
956 C<show('/politics/sidebar')> in the C<page> template. Running this template:
957  
958 Template::Declare->init( dispatch_to => ['MyApp::Render::Politics'] );
959 print Template::Declare->show( page => $page );
960  
961 Yields output using the value of the subclass's C<img_path()> method -- that
962 is, the sidebar image is now F</politics/ui/css/sidebar.png> instead of
963 F</ui/css/sidebar.png>:
964  
965 <h1>My page title</h1>
966 <p>Page paragraph</p>
967 <div class="sidebar">
968 <img src="/politics/ui/css/sidebar.png" />
969 <p>Sidebar paragraph</p>
970 <p>Another paragraph</p>
971 </div>
972  
973 =head3 Other Tricks
974  
975 The delegation behavior of C<alias> actually makes it a decent choice for
976 template authors to mix and match libraries of template classes as
977 appropriate, without worrying about side effects. You can even alias templates
978 in one template class into another template class if you're not the author of
979 that class by using the C<into> keyword:
980  
981 alias My::UI::Widgets into Your::UI::View under '/widgets';
982  
983 Now the templates defined in C<Your::UI::View> are available in
984 C<My::UI::Widgets> under C</widgets>. The C<mix> method supports this syntax
985 as well, though it's not necessarily recommended, given that you would not be
986 able to fulfill any contracts unless you re-opened the class into which you
987 mixed the templates. But in any case, authors of framework view classes might
988 find this functionality useful for automatically aliasing template classes
989 into a single dispatch template class.
990  
991 Another trick is to alias or mix your templates with package variables
992 specific to the composition. Do so via the C<setting> keyword:
993  
994 package My::Templates;
995 mix Some::Mixin under '/mymix', setting { name => 'Larry' };
996  
997 The templates mixed from C<Some::Mixin> into C<My::Templates> have package
998 variables set for them that are accessible I<only> from their mixed-in paths.
999 For example, if this template was defined in C<Some::Mixin>:
1000  
1001 template howdy => sub {
1002 my $self = shift;
1003 outs "Howdy, " . $self->package_variable('name') || 'Jesse';
1004 };
1005  
1006 Then C<show('mymix/howdy')> called on C<My::Templates> will output "Howdy,
1007 Larry", while the output from C<show('howdy')> will output "Howdy, Jesse". In
1008 other words, package variables defined for the mixed-in templates are
1009 available only to the mixins and not to the original. The same functionality
1010 exists for C<alias> as well.
1011  
1012 =begin comment
1013  
1014 =head2 Tag Sets
1015  
1016 Wherein we will eventually provide a brief tutorial on creating custom tag sets.
1017  
1018 =end comment
1019  
1020 =head1 METHODS
1021  
1022 =head2 init
1023  
1024 This I<class method> initializes the C<Template::Declare> system.
1025  
1026 =over
1027  
1028 =item dispatch_to
1029  
1030 An array reference of classes to search for templates. Template::Declare will
1031 search this list of classes in order to find a template path.
1032  
1033 =item roots
1034  
1035 B<Deprecated.> Just like C<dispatch_to>, only the classes are searched in
1036 reverse order. Maintained for backward compatibility and for the pleasure of
1037 those who want to continue using Template::Declare the way that Jesse's
1038 "crack-addled brain" intended.
1039  
1040 =item postprocessor
1041  
1042 A coderef called to postprocess the HTML or XML output of your templates. This
1043 is to alleviate using Tags for simple text markup.
1044  
1045 =item around_template
1046  
1047 A coderef called B<instead> of rendering each template. The coderef will
1048 receive three arguments: a coderef to invoke to render the template, the
1049 template's path, an arrayref of the arguments to the template, and the coderef
1050 of the template itself. You can use this for instrumentation. For example:
1051  
1052 Template::Declare->init(around_template => sub {
1053 my ($orig, $path, $args, $code) = @_;
1054 my $start = time;
1055 $orig->();
1056 warn "Rendering $path took " . (time - $start) . " seconds.";
1057 });
1058  
1059 =back
1060  
1061 =cut
1062  
1063 sub init {
1064 my $class = shift;
1065 my %args = (@_);
1066  
1067 if ( $args{'dispatch_to'} ) {
1068 $class->dispatch_to( $args{'dispatch_to'} );
1069 } elsif ( $args{'roots'} ) {
1070 $class->roots( $args{'roots'} );
1071 }
1072  
1073 if ( $args{'postprocessor'} ) {
1074 $class->postprocessor( $args{'postprocessor'} );
1075 }
1076  
1077 if ( $args{'around_template'} ) {
1078 $class->around_template( $args{'around_template'} );
1079 }
1080  
1081 }
1082  
1083 =head2 show TEMPLATE_NAME
1084  
1085 Template::Declare->show( 'howdy', name => 'Larry' );
1086 my $output = Template::Declare->show('index');
1087  
1088 Call C<show> with a C<template_name> and C<Template::Declare> will render that
1089 template. Subsequent arguments will be passed to the template. Content
1090 generated by C<show()> can be accessed via the C<output()> method if the
1091 output method you've chosen returns content instead of outputting it directly.
1092  
1093 If called in scalar context, this method will also just return the content
1094 when available.
1095  
1096 =cut
1097  
1098 sub show {
1099 my $class = shift;
1100 my $template = shift;
1101 local %Template::Declare::Tags::ELEMENT_ID_CACHE = ();
1102 return Template::Declare::Tags::show_page($template => @_);
1103 }
1104  
1105 =head2 Template Composition
1106  
1107 Sometimes you want to mix templates from one class into another class, or
1108 delegate template execution to a class of templates. C<alias()> and C<mix()>
1109 are your keys to doing so.
1110  
1111 =head3 mix
1112  
1113 mix Some::Clever::Mixin under '/mixin';
1114 mix Some::Other::Mixin under '/otmix', setting { name => 'Larry' };
1115 mix My::Mixin into My::View, under '/mymix';
1116  
1117 Mixes templates from one template class into another class. When the mixed-in
1118 template is called, its invocant will be the class into which it was mixed.
1119 This type of composition is known as a "mixin" in object-oriented parlance.
1120 See L<Template Composition|/"Template Composition"> for extended examples and
1121 a comparison to C<alias>.
1122  
1123 The first parameter is the name of the template class to be mixed in. The
1124 C<under> keyword tells C<mix> where to put the templates. For example,
1125 a C<foo> template in C<Some::Clever::Mixin> will be mixed in as C<mymixin/foo>.
1126  
1127 The C<setting> keyword specifies package variables available only to the
1128 mixed-in copies of templates. These are available to the templates as
1129 C<< $self->package_variable($varname) >>.
1130  
1131 The C<into> keyword tells C<mix> into what class to mix the templates. Without
1132 this keyword, C<mix> will mix them into the calling class.
1133  
1134 For those who prefer a direct OO syntax for mixins, just call C<mix()> as a
1135 method on the class to be mixed in. To replicate the above three examples
1136 without the use of the sugar:
1137  
1138 Some::Clever::Mixin->mix( '/mixin' );
1139 Some::Other::Mixin->mix( '/otmix', { name => 'Larry' } );
1140 My::Mixin->mix( 'My::View', '/mymix' );
1141  
1142 =cut
1143  
1144 sub mix {
1145 my $mixin = shift;
1146 my ($into, @args) = _into(@_);
1147 $mixin->_import($into, $into, @args);
1148 }
1149  
1150 =head3 alias
1151  
1152 alias Some::Clever:Templates under '/delegate';
1153 alias Some::Other::Templates under '/send_to', { name => 'Larry' };
1154 alias UI::Stuff into My::View, under '/mystuff';
1155  
1156 Aliases templates from one template class into another class. When an alias
1157 called, its invocant will be the class from which it was aliased. This type of
1158 composition is known as "delegation" in object-oriented parlance. See
1159 L<Template Composition|/"Template Composition"> for extended examples and a
1160 comparison to C<mix>.
1161  
1162 The first parameter is the name of the template class to alias. The C<under>
1163 keyword tells C<alias> where to put the templates. For example, a C<foo>
1164 template in C<Some::Clever::Templates> will be aliased as C<delegate/foo>.
1165  
1166 The C<setting> keyword specifies package variables available only to the
1167 aliases. These are available to the templates as
1168 C<< $self->package_variable($varname) >>.
1169  
1170 The C<into> keyword tells C<alias> into what class to alias the templates.
1171 Without this keyword, C<alias> will alias them into the calling class.
1172  
1173 For those who prefer a direct OO syntax for mixins, just call C<alias()> as a
1174 method on the class to be mixed in. To replicate the above three examples
1175 without the use of the sugar:
1176  
1177 Some::Clever:Templates->alias( '/delegate' );
1178 Some::Other::Templates->alias( '/send_to', { name => 'Larry' } );
1179 UI::Stuff->alias( 'My::View', '/mystuff' );
1180  
1181 =cut
1182  
1183 sub alias {
1184 my $mixin = shift;
1185 my ($into, @args) = _into(@_);
1186 $mixin->_import($into, undef, @args);
1187 }
1188  
1189 =head3 package_variable( VARIABLE )
1190  
1191 $td->package_variable( $varname => $value );
1192 $value = $td->package_variable( $varname );
1193  
1194 Returns a value set for a mixed-in template's variable, if any were specified
1195 when the template was mixed-in. See L</mix> for details.
1196  
1197 =cut
1198  
1199 sub package_variable {
1200 my $self = shift;
1201 my $var = shift;
1202 if (@_) {
1203 $TEMPLATE_VARS->{$self}->{$var} = shift;
1204 }
1205 return $TEMPLATE_VARS->{$self}->{$var};
1206 }
1207  
1208 =head3 package_variables( VARIABLE )
1209  
1210 $td->package_variables( $variables );
1211 $variables = $td->package_variables;
1212  
1213 Get or set a hash reference of variables for a mixed-in template. See
1214 L</mix> for details.
1215  
1216 =cut
1217  
1218 sub package_variables {
1219 my $self = shift;
1220 if (@_) {
1221 %{ $TEMPLATE_VARS->{$self} } = shift;
1222 }
1223 return $TEMPLATE_VARS->{$self};
1224 }
1225  
1226 =head2 Templates registration and lookup
1227  
1228 =head3 resolve_template TEMPLATE_PATH INCLUDE_PRIVATE_TEMPLATES
1229  
1230 my $code = Template::Declare->resolve_template($template);
1231 my $code = Template::Declare->has_template($template, 1);
1232  
1233 Turns a template path (C<TEMPLATE_PATH>) into a C<CODEREF>. If the
1234 boolean C<INCLUDE_PRIVATE_TEMPLATES> is true, resolves private template
1235 in addition to public ones. C<has_template()> is an alias for this method.
1236  
1237 First it looks through all the valid Template::Declare classes defined via
1238 C<dispatch_to>. For each class, it looks to see if it has a template called
1239 $template_name directly (or via a mixin).
1240  
1241 =cut
1242  
1243 sub resolve_template {
1244 my $self = shift;
1245 my $template_name = shift;
1246 my $show_private = shift || 0;
1247  
1248 my @search_packages;
1249  
1250 # If we're being called as a class method on T::D it means "search in any package"
1251 # Otherwise, it means search only in this specific package"
1252 if ( $self eq __PACKAGE__ ) {
1253 @search_packages = @{ Template::Declare->dispatch_to };
1254 } else {
1255 @search_packages = ($self);
1256 }
1257  
1258 foreach my $package (@search_packages) {
1259 next unless ( $package and $package->isa(__PACKAGE__) );
1260 if ( my $coderef = $package->_has_template( $template_name, $show_private ) ) {
1261 return $coderef;
1262 }
1263 }
1264 }
1265  
1266 =head3 has_template TEMPLATE_PATH INCLUDE_PRIVATE_TEMPLATES
1267  
1268 An alias for C<resolve_template>.
1269  
1270 =cut
1271  
1272 sub has_template { resolve_template(@_) }
1273  
1274 =head3 register_template( TEMPLATE_NAME, CODEREF )
1275  
1276 MyApp::Templates->register_template( howdy => sub { ... } );
1277  
1278 This method registers a template called C<TEMPLATE_NAME> in the calling class.
1279 As you might guess, C<CODEREF> defines the template's implementation. This
1280 method is mainly intended to be used internally, as you use the C<template>
1281 keyword to create templates, right?
1282  
1283 =cut
1284  
1285 sub register_template {
1286 my $class = shift;
1287 my $template_name = shift;
1288 my $code = shift;
1289 push @{ __PACKAGE__->templates()->{$class} }, $template_name;
1290 _register_template( $class, _template_name_to_sub($template_name), $code )
1291 }
1292  
1293 =head3 register_private_template( TEMPLATE_NAME, CODEREF )
1294  
1295 MyApp::Templates->register_private_template( howdy => sub { ... } );
1296  
1297 This method registers a private template called C<TEMPLATE_NAME> in the
1298 calling class. As you might guess, C<CODEREF> defines the template's
1299 implementation.
1300  
1301 Private templates can't be called directly from user code but only from other
1302 templates.
1303  
1304 This method is mainly intended to be used internally, as you use the
1305 C<private template> expression to create templates, right?
1306  
1307 =cut
1308  
1309 sub register_private_template {
1310 my $class = shift;
1311 my $template_name = shift;
1312 my $code = shift;
1313 push @{ __PACKAGE__->private_templates()->{$class} }, $template_name;
1314 _register_template( $class, _template_name_to_private_sub($template_name), $code );
1315  
1316 }
1317  
1318 =head3 buffer
1319  
1320 Gets or sets the L<String::BufferStack> object; this is a class method.
1321  
1322 You can use it to manipulate the output from tags as they are output. It's used
1323 internally to make the tags nest correctly, and be output to the right place.
1324 We're not sure if there's ever a need for you to frob it by hand, but it does
1325 enable things like the following:
1326  
1327 template simple => sub {
1328 html {
1329 head {}
1330 body {
1331 Template::Declare->buffer->set_filter( sub {uc shift} );
1332 p { 'Whee!' }
1333 p { 'Hello, world wide web!' }
1334 Template::Declare->buffer->clear_top if rand() < 0.5;
1335 }
1336 }
1337 };
1338  
1339 ...which outputs, with equal regularity, either:
1340  
1341 <html>
1342 <head></head>
1343 <body>
1344 <P>WHEE!</P>
1345 <P>HELLO, WORLD WIDE WEB!</P>
1346 </body>
1347 </html>
1348  
1349 ...or:
1350  
1351 <html>
1352 <head></head>
1353 <body></body>
1354 </html>
1355  
1356 We'll leave it to you to judge whether or not that's actually useful.
1357  
1358 =head2 Helpers
1359  
1360 You don't need to call any of this directly.
1361  
1362 =head3 into
1363  
1364 $class = into $class;
1365  
1366 C<into> is a helper method providing semantic sugar for the L</mix> method.
1367 All it does is return the name of the class on which it was called.
1368  
1369 =cut
1370  
1371 sub into { shift }
1372  
1373 =head2 Old, deprecated or just better to avoid
1374  
1375 =head3 import_templates
1376  
1377 import_templates MyApp::Templates under '/something';
1378  
1379 Like C<mix()>, but without support for the C<into> or C<setting> keywords.
1380 That is, it mixes templates into the calling template class and does not
1381 support package variables for those mixins.
1382  
1383 B<Deprecated> in favor of L</mix>. Will be supported for a long time, but
1384 new code should use C<mix()>.
1385  
1386 =cut
1387  
1388 sub import_templates {
1389 my $caller = scalar caller(0);
1390 shift->_import($caller, $caller, @_);
1391 }
1392  
1393 =head3 new_buffer_frame
1394  
1395 $td->new_buffer_frame;
1396 # same as
1397 $td->buffer->push( private => 1 );
1398  
1399 Creates a new buffer frame, using L<String::BufferStack/push> with C<private>.
1400  
1401 B<Deprecated> in favor of dealing with L</buffer> directly.
1402  
1403 =cut
1404  
1405 sub new_buffer_frame {
1406 __PACKAGE__->buffer->push( private => 1 );
1407 }
1408  
1409 =head3 end_buffer_frame
1410  
1411 my $buf = $td->end_buffer_frame;
1412 # same as
1413 my $buf = $td->buffer->pop;
1414  
1415 Deletes and returns the topmost buffer, using L<String::BufferStack/pop>.
1416  
1417 B<Deprecated> in favor of dealing with L</buffer> directly.
1418  
1419 =cut
1420  
1421 sub end_buffer_frame {
1422 __PACKAGE__->buffer->pop;
1423 }
1424  
1425 =head3 path_for $template
1426  
1427 my $path = Template::Declare->path_for('index');
1428  
1429 Returns the path for the template name to be used for show, adjusted with
1430 paths used in C<mix>. Note that this will only work for the last class into
1431 which you imported the template. This method is, therefore, deprecated.
1432  
1433 =cut
1434  
1435 # Deprecated in favor of dispatch_to().
1436 sub roots {
1437 # warn "roots() has been deprecated; use dispatch_to() instead\n";
1438 my $class = shift;
1439 $class->dispatch_to( [ reverse @{ +shift } ] ) if @_;
1440 return [ reverse @{ $class->dispatch_to } ];
1441 }
1442  
1443 # Removed methods that no longer work (and were never documented anyway).
1444 # Remove these no-ops after a few releases (added for 0.41).
1445  
1446 =begin comment
1447  
1448 =head3 aliases
1449  
1450 =head3 alias_metadata
1451  
1452 =end comment
1453  
1454 =cut
1455  
1456 sub aliases {
1457 require Carp;
1458 Carp::cluck( 'aliases() is a deprecated no-op' );
1459 }
1460  
1461 sub alias_metadata {
1462 require Carp;
1463 Carp::cluck( 'alias_metadata() is a deprecated no-op' );
1464 }
1465  
1466 sub path_for {
1467 my $class = shift;
1468 my $template = shift;
1469 return ($class->imported_into ||'') . '/' . $template;
1470 }
1471  
1472 sub _templates_for {
1473 my $tmpl = shift->templates->{+shift} or return;
1474 return wantarray ? @{ $tmpl } : $tmpl;
1475 }
1476  
1477 sub _private_templates_for {
1478 my $tmpl = shift->private_templates->{+shift} or return;
1479 return wantarray ? @{ $tmpl } : $tmpl;
1480 }
1481  
1482 sub _has_template {
1483 # Otherwise find only in specific package
1484 my $pkg = shift;
1485 my $template_name = shift;
1486 my $show_private = 0 || shift;
1487  
1488 if ( my $coderef = $pkg->_find_template_sub( _template_name_to_sub($template_name) ) ) {
1489 return $coderef;
1490 } elsif ( $show_private and $coderef = $pkg->_find_template_sub( _template_name_to_private_sub($template_name))) {
1491 return $coderef;
1492 }
1493  
1494 return undef;
1495 }
1496  
1497 sub _dispatch_template {
1498 my $class = shift;
1499 my $code = shift;
1500 unshift @_, $class;
1501 goto $code;
1502 }
1503  
1504 sub _find_template_sub {
1505 my $self = shift;
1506 my $subname = shift;
1507 return $self->can($subname);
1508 }
1509  
1510 sub _template_name_to_sub {
1511 return _subname( "_jifty_template_", shift );
1512 }
1513  
1514 sub _template_name_to_private_sub {
1515 return _subname( "_jifty_private_template_", shift );
1516 }
1517  
1518 sub _subname {
1519 my $prefix = shift;
1520 my $template = shift || '';
1521 $template =~ s{/+}{/}g;
1522 $template =~ s{^/}{};
1523 return join( '', $prefix, $template );
1524 }
1525  
1526 sub _register_template {
1527 my $self = shift;
1528 my $class = ref($self) || $self;
1529 my $subname = shift;
1530 my $coderef = shift;
1531 no strict 'refs';
1532 no warnings 'redefine';
1533 *{ $class . '::' . $subname } = $coderef;
1534 }
1535  
1536 sub _into {
1537 my ($into, $under);
1538 if ( eval { $_[0]->isa(__PACKAGE__) } ) {
1539 ($into, $under) = (shift, shift);
1540 } elsif ( eval { $_[1]->isa(__PACKAGE__) } ) {
1541 ($under, $into) = (shift, shift);
1542 } else {
1543 $into = caller(1);
1544 $under = shift;
1545 }
1546 return $into, $under, @_;
1547 }
1548  
1549 sub _import {
1550 return undef if $_[0] eq __PACKAGE__;
1551 my ($mixin, $into, $invocant, $prefix, $vars) = @_;
1552  
1553  
1554 $prefix =~ s|/+/|/|g;
1555 $prefix =~ s|/$||;
1556 $mixin->imported_into($prefix);
1557  
1558 my @packages = reverse grep { $_->isa(__PACKAGE__) }
1559 Class::ISA::self_and_super_path( $mixin );
1560  
1561 foreach my $from (@packages) {
1562 for my $tname ( __PACKAGE__->_templates_for($from) ) {
1563 my $sname = _template_name_to_sub($tname);
1564 $into->register_template(
1565 "$prefix/$tname",
1566 _import_code( $sname, $from, $invocant || $mixin, $vars )
1567 );
1568 }
1569 for my $tname ( __PACKAGE__->_private_templates_for($from) ) {
1570 my $sname = _template_name_to_private_sub($tname);
1571 $into->register_private_template(
1572 "$prefix/$tname",
1573 _import_code( $sname, $from, $invocant || $mixin, $vars )
1574 );
1575 }
1576 }
1577 }
1578  
1579 sub _import_code {
1580 my ($sname, $from, $mixin, $vars) = @_;
1581 my $code = $from->_find_template_sub( $sname );
1582 return $mixin eq $from ? $code : sub { shift; $code->($mixin, @_) }
1583 unless $vars;
1584 return sub {
1585 shift @_; # Get rid of the passed-in "$self" class.
1586 local $TEMPLATE_VARS->{$mixin} = $vars;
1587 $code->($mixin, @_);
1588 };
1589 }
1590  
1591 =head1 PITFALLS
1592  
1593 We're reusing the perl interpreter for our templating language, but Perl was
1594 not designed specifically for our purpose here. Here are some known pitfalls
1595 while you're scripting your templates with this module.
1596  
1597 =over
1598  
1599 =item *
1600  
1601 It's quite common to see tag sub calling statements without trailing
1602 semi-colons right after C<}>. For instance,
1603  
1604 template foo => sub {
1605 p {
1606 a { attr { src => '1.png' } }
1607 a { attr { src => '2.png' } }
1608 a { attr { src => '3.png' } }
1609 }
1610 };
1611  
1612 is equivalent to
1613  
1614 template foo => sub {
1615 p {
1616 a { attr { src => '1.png' } };
1617 a { attr { src => '2.png' } };
1618 a { attr { src => '3.png' } };
1619 };
1620 };
1621  
1622 But C<xml_decl> is a notable exception. Please always put a trailing semicolon
1623 after C<xml_decl { ... }>, or you'll mess up the order of output.
1624  
1625 =item *
1626  
1627 Another place that requires trailing semicolon is the statements before a Perl
1628 looping statement, an if statement, or a C<show> call. For example:
1629  
1630 p { "My links:" };
1631 for (@links) {
1632 with ( src => $_ ), a {}
1633 }
1634  
1635 The C<;> after C< p { ... } > is required here, or Perl will complain about
1636 syntax errors.
1637  
1638 Another example is
1639  
1640 h1 { 'heading' }; # this trailing semicolon is mandatory
1641 show 'tag_tag'
1642  
1643 =item *
1644  
1645 The C<is> syntax for declaring tag attributes also requires a trailing
1646 semicolon, unless it is the only statement in a block. For example,
1647  
1648 p { class is 'item'; id is 'item1'; outs "This is an item" }
1649 img { src is 'cat.gif' }
1650  
1651 =item *
1652  
1653 Literal strings that have tag siblings won't be captured. So the following template
1654  
1655 p { 'hello'; em { 'world' } }
1656  
1657 produces
1658  
1659 <p>
1660 <em>world</em>
1661 </p>
1662  
1663 instead of the desired output
1664  
1665 <p>
1666 hello
1667 <em>world</em>
1668 </p>
1669  
1670 You can use C<outs> here to solve this problem:
1671  
1672 p { outs 'hello'; em { 'world' } }
1673  
1674 Note you can always get rid of C<outs> if the string literal is the only
1675 element of the containing block:
1676  
1677 p { 'hello, world!' }
1678  
1679 =item *
1680  
1681 Look out! If the if block is the last block/statement and the condition part
1682 is evaluated to be 0:
1683  
1684 p { if ( 0 ) { } }
1685  
1686 produces
1687  
1688 <p>0</p>
1689  
1690 instead of the more intuitive output:
1691  
1692 <p></p>
1693  
1694 This is because C<if ( 0 )> is the last expression, so C<0> is returned as the
1695 value of the whole block, which is used as the content of <p> tag.
1696  
1697 To get rid of this, just put an empty string at the end so it returns empty
1698 string as the content instead of 0:
1699  
1700 p { if ( 0 ) { } '' }
1701  
1702 =back
1703  
1704 =head1 BUGS
1705  
1706 Crawling all over, baby. Be very, very careful. This code is so cutting edge,
1707 it can only be fashioned from carbon nanotubes. But we're already using this
1708 thing in production :) Make sure you have read the L</PITFALLS>
1709 section above :)
1710  
1711 Some specific bugs and design flaws that we'd love to see fixed.
1712  
1713 =over
1714  
1715 =item Output isn't streamy.
1716  
1717 =back
1718  
1719 If you run into bugs or misfeatures, please report them to
1720 C<bug-template-declare@rt.cpan.org>.
1721  
1722 =head1 SEE ALSO
1723  
1724 =over
1725  
1726 =item L<Template::Declare::Tags>
1727  
1728 =item L<Template::Declare::TagSet>
1729  
1730 =item L<Template::Declare::TagSet::HTML>
1731  
1732 =item L<Template::Declare::TagSet::XUL>
1733  
1734 =item L<Jifty>
1735  
1736 =back
1737  
1738 =head1 AUTHOR
1739  
1740 Jesse Vincent <jesse@bestpractical.com>
1741  
1742 =head1 LICENSE
1743  
1744 Template::Declare is Copyright 2006-2009 Best Practical Solutions, LLC.
1745  
1746 Template::Declare is distributed under the same terms as Perl itself.
1747  
1748 =cut
1749  
1750 1;