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