277195bdc4f693fbfde468ae7ed07461761e1b51
[urisagit/Template-Simple.git] / lib / Template / Simple.pm
1 package Template::Simple;
2
3 use warnings;
4 use strict;
5
6 use Carp ;
7 use Scalar::Util qw( reftype ) ;
8 use File::Slurp ;
9
10 use Data::Dumper ;
11
12 our $VERSION = '0.03';
13
14 my %opt_defaults = (
15
16         pre_delim       => qr/\[%/,
17         post_delim      => qr/%\]/,
18         greedy_chunk    => 0,
19 #       upper_case      => 0,
20 #       lower_case      => 0,
21         include_paths   => [ qw( templates ) ],
22 ) ;
23
24 sub new {
25
26         my( $class, %opts ) = @_ ;
27
28         my $self = bless {}, $class ;
29
30 # get all the options or defaults into the object
31
32         while( my( $name, $default ) = each %opt_defaults ) {
33
34                 $self->{$name} = defined( $opts{$name} ) ? 
35                                 $opts{$name} : $default ;
36         }
37
38 # make up the regexes to parse the markup from templates
39
40 # this matches scalar markups and grabs the name
41
42         $self->{scalar_re} = qr{
43                 $self->{pre_delim}
44                 \s*                     # optional leading whitespace
45                 (\w+?)                  # grab scalar name
46                 \s*                     # optional trailing whitespace
47                 $self->{post_delim}
48         }xi ;                           # case insensitive
49
50 #print "RE <$self->{scalar_re}>\n" ;
51
52 # this grabs the body of a chunk in either greedy or non-greedy modes
53
54         my $chunk_body = $self->{greedy_chunk} ? qr/.+/s : qr/.+?/s ;
55
56 # this matches a marked chunk and grabs its name and text body
57
58         $self->{chunk_re} = qr{
59                 $self->{pre_delim}
60                 \s*                     # optional leading whitespace
61                 START                   # required START token
62                 \s+                     # required whitespace
63                 (\w+?)                  # grab the chunk name
64                 \s*                     # optional trailing whitespace
65                 $self->{post_delim}
66                 ($chunk_body)           # grab the chunk body
67                 $self->{pre_delim}
68                 \s*                     # optional leading whitespace
69                 END                     # required END token
70                 \s+                     # required whitespace
71                 \1                      # match the grabbed chunk name
72                 \s*                     # optional trailing whitespace
73                 $self->{post_delim}
74         }xi ;                           # case insensitive
75
76 #print "RE <$self->{chunk_re}>\n" ;
77
78 # this matches a include markup and grabs its template name
79
80         $self->{include_re} = qr{
81                 $self->{pre_delim}
82                 \s*                     # optional leading whitespace
83                 INCLUDE                 # required INCLUDE token
84                 \s+                     # required whitespace
85                 (\w+?)                  # grab the included template name
86                 \s*                     # optional trailing whitespace
87                 $self->{post_delim}
88         }xi ;                           # case insensitive
89
90 # load in any templates
91
92         $self->add_templates( $opts{templates} ) ;
93
94         return $self ;
95 }
96
97 sub compile {
98
99         my( $self, $template_name ) = @_ ;
100
101         my $tmpl_ref = eval {
102                  $self->_get_template( $template_name ) ;
103         } ;
104
105         croak "Template::Simple $@" if $@ ;
106
107 # compile a copy of the template as it will be destroyed
108
109         my $code_body = $self->_compile_chunk( '', "${$tmpl_ref}", "\t" ) ;
110
111         my $source = <<CODE ;
112
113 no warnings ;
114
115 sub {
116         my( \$data ) = \@_ ;
117
118         my \$out = $code_body ;
119
120         return \\\$out ;
121 }
122 CODE
123
124 #print $source ;
125
126         my $code_ref = eval $source ;
127
128 die $@ if $@ ;
129
130         $self->{compiled_cache}{$template_name} = $code_ref ;
131         $self->{source_cache}{$template_name} = $source ;
132 }
133
134 sub get_source {
135
136         my( $self, $template_name ) = @_ ;
137
138         return $self->{source_cache}{$template_name} ;
139 }
140
141
142 sub _compile_chunk {
143
144         my( $self, $chunk_name, $template, $indent ) = @_ ;
145
146         return '' unless length $template ;
147
148         my @parts ;
149
150 # loop all nested chunks and the text separating them
151
152         while( $template =~ m{$self->{chunk_re}}g ) {
153
154 # grab the pre-match text and compile its scalars and save all of its parts
155
156                 push @parts, $self->_compile_scalars(
157                                 substr( $template, 0, $-[0] ) ) ;
158
159 # compile the nested chunk and save its parts
160
161                 push @parts, $self->_compile_chunk( $1, $2, "$indent\t\t" ) ;
162
163 # chop off the pre-match and the chunk
164
165                 substr( $template, 0, $+[0], '' ) ;
166         }
167
168 # compile trailing text for scalars and save all of its parts
169
170         push @parts, $self->_compile_scalars( $template ) ;
171
172 # generate the code for this chunk
173
174 # start it with a do{} block open
175
176         my $code = <<CODE ;
177 do {
178 CODE
179
180         $indent .= "\t" ;
181
182 # generate a lookup in data for this chunk name (unless it is the top
183 # level). this descends down the data tree during rendering
184
185         $code .= <<CODE if $chunk_name ;
186 ${indent}my \$data = \$data->{$chunk_name} ;
187 CODE
188
189 # add the loop code to handle a scalar or an array
190
191         $code .= <<CODE ;
192 ${indent}my \$out ;
193 ${indent}foreach my \$data ( ref \$data eq 'ARRAY' ? \@{\$data} : \$data ) {
194
195         ${indent}\$out .= ref \$data ne 'HASH' ? \$data :
196 CODE
197
198         $indent .= "\t" ;
199
200 # now generate the code to output all the parts of this chunk. they
201 # are all concatentated by the . operator
202
203         $code .= $indent . join( "\n$indent.\n$indent", @parts ) ;
204
205         chop $indent ;
206
207 # now we end the .= statement, the loop and the do block for this chunk
208         $code .= <<CODE ;
209  ;
210 $indent}
211 $indent\$out ;
212 CODE
213
214         chop $indent ;
215         $code .= "$indent}" ;
216
217         return $code ;
218 }
219
220 sub _compile_scalars {
221
222         my( $self, $template ) = @_ ;
223
224 # if the template is empty return no parts
225
226         return unless length $template ;
227
228         my @parts ;
229
230         while( $template =~ m{$self->{scalar_re}}g ) {
231
232 # keep the text before the scalar markup and the code to access the scalar
233
234                 push( @parts,
235                         dump_text( substr( $template, 0, $-[0] ) ),
236                         "\$data->{$1}"
237                 ) ;
238                 substr( $template, 0, $+[0], '' ) ;
239         }
240
241 # keep any trailing text part
242
243         push @parts, dump_text( $template ) ;
244
245         return @parts ;
246 }
247
248 use Data::Dumper ;
249
250 sub dump_text {
251
252         my( $text ) = @_ ;
253
254         return unless length $text ;
255
256         local( $Data::Dumper::Useqq ) = 1 ;
257
258         my $dumped = Dumper $text ;
259
260         $dumped =~ s/^[^"]+// ;
261         $dumped =~ s/;\n$// ;
262
263         return $dumped ;
264 }
265
266 sub render {
267
268         my( $self, $template_name, $data ) = @_ ;
269
270         my $tmpl_ref = ref $template_name eq 'SCALAR' ? $template_name : '' ;
271
272         unless( $tmpl_ref ) {
273
274 # render with cached code and return if we precompiled this template
275
276                 if ( my $compiled = $self->{compiled_cache}{$template_name} ) {
277
278                         return $compiled->($data) ;
279                 }
280
281 # not compiled so get this template by name
282
283                 $tmpl_ref ||= eval{ $self->_get_template($template_name) } ;
284
285 # we couldn't find this template name so assume it is the template text
286
287                 $tmpl_ref ||= \$template_name ;
288         }
289
290         my $rendered = $self->_render_includes( $tmpl_ref ) ;
291
292 #print "INC EXP <$rendered>\n" ;
293
294         $rendered = eval {
295                  $self->_render_chunk( $rendered, $data ) ;
296         } ;
297
298         croak "Template::Simple $@" if $@ ;
299
300         return $rendered ;
301 }
302
303 sub _render_includes {
304
305         my( $self, $tmpl_ref ) = @_ ;
306
307 # make a copy of the initial template so we can render it.
308
309         my $rendered = ${$tmpl_ref} ;
310
311 # loop until we can render no more include markups
312
313         1 while $rendered =~
314                  s{$self->{include_re}}
315                     { ${ $self->_get_template($1) }
316                   }e ;
317
318         return \$rendered ;
319 }
320
321 my %renderers = (
322
323         HASH    => \&_render_hash,
324         ARRAY   => \&_render_array,
325         CODE    => \&_render_code,
326 # if no ref then data is a scalar so replace the template with just the data
327         ''      => sub { \$_[2] },
328 ) ;
329
330
331 sub _render_chunk {
332
333         my( $self, $tmpl_ref, $data ) = @_ ;
334
335 #print "T ref [$tmpl_ref] [$$tmpl_ref]\n" ;
336 #print "CHUNK ref [$tmpl_ref] TMPL\n<$$tmpl_ref>\n" ;
337
338 #print Dumper $data ;
339
340         return \'' unless defined $data ;
341
342 # now render this chunk based on the type of data
343
344         my $renderer = $renderers{reftype $data || ''} ;
345
346 #print "EXP $renderer\nREF ", reftype $data, "\n" ;
347
348         die "unknown template data type '$data'\n" unless defined $renderer ;
349
350         return $self->$renderer( $tmpl_ref, $data ) ;
351 }
352
353 sub _render_hash {
354
355         my( $self, $tmpl_ref, $href ) = @_ ;
356
357         return $tmpl_ref unless keys %{$href} ;
358
359 # we need a local copy of the template to render
360
361         my $rendered = ${$tmpl_ref}      ;
362
363
364 # recursively render all top level chunks in this chunk
365
366         $rendered =~ s{$self->{chunk_re}}
367                       {
368                         # print "CHUNK $1\nBODY\n----\n<$2>\n\n------\n" ;
369                         print "CHUNK $1\nBODY\n----\n<$2>\n\n------\n" ;
370                         print "pre CHUNK [$`]\n" ;
371                         ${ $self->_render_chunk( \"$2", $href->{$1} ) }
372                       }gex ;
373
374 # now render scalars
375
376 #print "HREF: ", Dumper $href ;
377
378         $rendered =~ s{$self->{scalar_re}}
379                       {
380                          # print "SCALAR $1 VAL $href->{$1}\n" ;
381                          defined $href->{$1} ? $href->{$1} : ''
382                       }ge ;
383
384 #print "HASH REND3\n<$rendered>\n" ;
385
386         return \$rendered ;
387 }
388
389 sub _render_array {
390
391         my( $self, $tmpl_ref, $aref ) = @_ ;
392
393 # render this $tmpl_ref for each element of the aref and join them
394
395         my $rendered ;
396
397 #print "AREF: ", Dumper $aref ;
398
399         $rendered .= ${$self->_render_chunk( $tmpl_ref, $_ )} for @{$aref} ;
400
401         return \$rendered ;
402 }
403
404 sub _render_code {
405
406         my( $self, $tmpl_ref, $cref ) = @_ ;
407
408         my $rendered = $cref->( $tmpl_ref ) ;
409
410         die <<DIE if ref $rendered ne 'SCALAR' ;
411 data callback to code didn't return a scalar or scalar reference
412 DIE
413
414         return $rendered ;
415 }
416
417 sub add_templates {
418
419         my( $self, $tmpls ) = @_ ;
420
421 #print Dumper $tmpls ;
422         return unless defined $tmpls ;
423
424         ref $tmpls eq 'HASH' or croak "templates argument is not a hash ref" ;
425
426 # copy all the templates from the arg hash and force the values to be
427 # scalar refs
428         
429         @{ $self->{tmpl_cache}}{ keys %{$tmpls} } =
430                 map ref $_ eq 'SCALAR' ? \"${$_}" : \"$_", values %{$tmpls} ;
431
432 #print Dumper $self->{tmpl_cache} ;
433
434         return ;
435 }
436
437 sub delete_templates {
438
439         my( $self, @names ) = @_ ;
440
441 # delete all the cached stuff or just the names passed in
442
443         @names = keys %{$self->{tmpl_cache}} unless @names ;
444
445 # clear out all the caches
446 # TODO: reorg these into a hash per name
447
448         delete @{$self->{tmpl_cache}}{ @names } ;
449         delete @{$self->{compiled_cache}}{ @names } ;
450         delete @{$self->{source_cache}}{ @names } ;
451
452 # also remove where we found it to force a fresh search
453
454         delete @{$self->{template_paths}}{ @names } ;
455
456         return ;
457 }
458
459 sub _get_template {
460
461         my( $self, $tmpl_name ) = @_ ;
462
463 #print "INC $tmpl_name\n" ;
464
465         my $tmpls = $self->{tmpl_cache} ;
466
467 # get the template from the cache and send it back if it was found there
468
469         my $template = $tmpls->{ $tmpl_name } ;
470         return $template if $template ;
471
472 # not found, so find, slurp in and cache the template
473
474         $template = $self->_find_template( $tmpl_name ) ;
475         $tmpls->{ $tmpl_name } = $template ;
476
477         return $template ;
478 }
479
480 sub _find_template {
481
482         my( $self, $tmpl_name ) = @_ ;
483
484         foreach my $dir ( @{$self->{include_paths}} ) {
485
486                 my $tmpl_path = "$dir/$tmpl_name.tmpl" ;
487
488 #print "PATH: $tmpl_path\n" ;
489                 next unless -r $tmpl_path ;
490
491 # cache the path to this template
492
493                 $self->{template_paths}{$tmpl_name} = $tmpl_path ;
494
495 # slurp in the template file and return it as a scalar ref
496
497                 return scalar read_file( $tmpl_path, scalar_ref => 1 ) ;
498         }
499
500         die <<DIE ;
501 can't find template '$tmpl_name' in '@{$self->{include_paths}}'
502 DIE
503
504 }
505
506 1; # End of Template::Simple
507
508 __END__
509
510 =head1 NAME
511
512 Template::Simple - A simple and fast template module
513
514 =head1 VERSION
515
516 Version 0.03
517
518 =head1 SYNOPSIS
519
520     use Template::Simple;
521
522     my $tmpl = Template::Simple->new();
523
524     my $template = <<TMPL ;
525 [%INCLUDE header%]
526 [%START row%]
527         [%first%] - [%second%]
528 [%END row%]
529 [%INCLUDE footer%]
530 TMPL
531
532     my $data = {
533         header  => {
534                 date    => 'Jan 1, 2008',
535                 author  => 'Me, myself and I',
536         },
537         row     => [
538                 {
539                         first   => 'row 1 value 1',
540                         second  => 'row 1 value 2',
541                 },
542                 {
543                         first   => 'row 2 value 1',
544                         second  => 'row 2 value 2',
545                 },
546         ],
547         footer  => {
548                 modified        => 'Aug 31, 2006',
549         },
550     } ;
551
552     my $rendered = $tmpl->render( $template, $data ) ;
553
554 =head1 DESCRIPTION
555
556 Template::Simple has these goals:
557
558 =over 4
559
560 =item * Support most common template operations
561
562 It can recursively include other templates, replace tokens (scalars),
563 recursively render nested chunks of text and render lists. By using
564 simple idioms you can get conditional renderings.
565
566 =item * Complete isolation of template from program code
567
568 This is very important as template design can be done by different
569 people than the program logic. It is rare that one person is well
570 skilled in both template design and also programming.
571
572 =item * Very simple template markup (only 4 markups)
573
574 The only markups are C<INCLUDE>, C<START>, C<END> and C<token>. See
575 MARKUP for more.
576
577 =item * Easy to follow rendering rules
578
579 Rendering of templates and chunks is driven from a data tree. The type
580 of the data element used in an rendering controls how the rendering
581 happens.  The data element can be a scalar or scalar reference or an
582 array, hash or code reference.
583
584 =item * Efficient template rendering
585
586 Rendering is very simple and uses Perl's regular expressions
587 efficiently. Because the markup is so simple less processing is needed
588 than many other templaters. Precompiling templates is not supported
589 yet but that optimization is on the TODO list.
590
591 =item * Easy user extensions
592
593 User code can be called during an rendering so you can do custom
594 renderings and plugins. Closures can be used so the code can have its
595 own private data for use in rendering its template chunk.
596
597 =back
598
599 =head2 new()
600
601 You create a Template::Simple by calling the class method new:
602
603         my $tmpl = Template::Simple->new() ;
604
605 All the arguments to C<new()> are key/value options that change how
606 the object will do renderings.
607
608 =over 4
609
610 =item   pre_delim
611
612 This option sets the string or regex that is the starting delimiter
613 for all markups. You can use a plain string or a qr// but you need to
614 escape (with \Q or \) any regex metachars if you want them to be plain
615 chars. The default is qr/\[%/.
616
617         my $tmpl = Template::Simple->new(
618                 pre_delim => '<%',
619         );
620
621         my $rendered = $tmpl->render( '<%FOO%]', 'bar' ) ;
622
623 =item   post_delim
624
625 This option sets the string or regex that is the ending delimiter
626 for all markups. You can use a plain string or a qr// but you need to
627 escape (with \Q or \) any regex metachars if you want them to be plain
628 chars. The default is qr/%]/.
629
630         my $tmpl = Template::Simple->new(
631                 post_delim => '%>',
632         );
633
634         my $rendered = $tmpl->render( '[%FOO%>', 'bar' ) ;
635
636 =item   greedy_chunk
637
638 This boolean option will cause the regex that grabs a chunk of text
639 between the C<START/END> markups to become greedy (.+). The default is
640 a not-greedy grab of the chunk text. (UNTESTED)
641
642 =item   templates
643
644 This option lets you load templates directly into the cache of the
645 Template::Simple object. This cache will be searched by the C<INCLUDE>
646 markup which will be replaced by the template if found. The option
647 value is a hash reference which has template names (the name in the
648 C<INCLUDE> markup) for keys and their template text as their
649 values. You can delete or clear templates from the object cache with
650 the C<delete_template> method.
651
652
653         my $tmpl = Template::Simple->new(
654                 templates       => {
655
656                         foo     => <<FOO,
657 [%baz%] is a [%quux%]
658 FOO
659                         bar     => <<BAR,
660 [%user%] is not a [%fool%]
661 BAR
662                 },
663         );
664
665         my $template = <<TMPL ;
666 [%INCLUDE foo %]
667 TMPL
668
669         my $rendered = $tmpl->render(
670                 $template,
671                 {
672                         baz => 'blue',
673                         quux => 'color,
674                 }
675         ) ;
676
677 =item   include_paths
678
679 Template::Simple can also load C<INCLUDE> templates from files. This
680 option lets you set the directory paths to search for those
681 files. Note that the template name in the C<INCLUDE> markup has the
682 .tmpl suffix appended to it when searched for in one of these
683 paths. The loaded file is cached inside the Template::Simple object
684 along with any loaded by the C<templates> option.
685
686 =back
687
688 =head1 METHODS
689
690 =head2 render
691
692 This method is passed a template and a data tree and it renders it and
693 returns a reference to the resulting string. The template argument can
694 be a scalar or a scalar reference. The data tree argument can be any
695 value allowed by Template::Simple when rendering a template. It can
696 also be a blessed reference (Perl object) since
697 C<Scalar::Util::reftype> is used instead of C<ref> to determine the
698 data type.
699
700 Note that the author recommends against passing in an object as this
701 breaks encapsulation and forces your object to be (most likely) a
702 hash. It would be better to create a simple method that copies the
703 object contents to a hash reference and pass that. But current
704 templaters allow passing in objects so that is supported here as well.
705
706     my $rendered = $tmpl->render( $template, $data ) ;
707
708 =head2 add_templates
709
710 This method adds templates to the object cache. It takes a list of template names and texts just like the C<templates> constructor option.
711
712         $tmpl->add_templates( 
713                 {
714                         foo     => \$foo_template,
715                         bar     => '[%include bar%]',
716                 }
717         ) ;
718
719 =head2 delete_templates
720
721 This method takes a list of template names and will delete them from
722 the template cache in the object. If you pass in an empty list then
723 all the templates will be deleted. This can be used when you know a
724 template file has been updated and you want to get it loaded back into
725 the cache. Note that you can delete templates that were loaded
726 directly (via the C<templates> constructor option or the
727 C<add_templates> method) or loaded from a file.
728
729     # this deletes only the foo and bar templates from the object cache
730
731         $tmpl->delete_templates( qw( foo bar ) ;
732
733     # this deletes all of templates from the object cache
734
735         $tmpl->delete_templates() ;
736
737 =head2 get_dependencies
738
739 This method render the only C<INCLUDE> markups of a template and it
740 returns a list of the file paths that were found and loaded. It is
741 meant to be used to build up a dependency list of included templates
742 for a main template. Typically this can be called from a script (see
743 TODO) that will do this for a set of main templates and will generate
744 Makefile dependencies for them. Then you can regenerate rendered
745 templates only when any of their included templates have changed. It
746 takes a single argument of a template.
747
748 UNKNOWN: will this require a clearing of the cache or will it do the
749 right thing on its own? or will it use the file path cache?
750
751         my @dependencies =
752                 $tmpl->get_dependencies( '[%INCLUDE top_level%]' );
753
754 =head1 MARKUP
755
756 All the markups in Template::Simple use the same delimiters which are
757 C<[%> and C<%]>. You can change the delimiters with the C<pre_delim>
758 and C<post_delim> options in the C<new()> constructor.
759
760 =head2 Tokens
761
762 A token is a single markup with a C<\w+> Perl word inside. The token
763 can have optional whitespace before and after it. A token is replaced
764 by a value looked up in a hash with the token as the key. The hash
765 lookup keeps the same case as parsed from the token markup.
766
767     [% foo %] [%BAR%]
768
769 Those will be replaced by C<$href->{foo}> and C<$href->{BAR}> assuming
770 C<$href> is the current data for this rendering. Tokens are only
771 parsed out during hash data rendering so see Hash Data for more.
772
773 =head2 Chunks
774
775 Chunks are regions of text in a template that are marked off with a
776 start and end markers with the same name. A chunk start marker is
777 C<[%START name%]> and the end marker for that chunk is C<[%END
778 name%]>. C<name> is a C<\w+> Perl word which is the name of this
779 chunk. The whitespace between C<START/END> and C<name> is required and
780 there is optional whitespace before C<START/END> and after the
781 C<name>. C<START/END> are case insensitive but the C<name>'s case is
782 kept. C<name> must match in the C<START/END> pair and it used as a key
783 in a hash data rendering. Chunks are the primary way to markup
784 templates for structures (sets of tokens), nesting (hashes of hashes),
785 repeats (array references) and callbacks to user code. Chunks are only
786 parsed out during hash data rendering so see Hash Data for more.
787
788 The body of text between the C<START/END> markups is grabbed with a
789 C<.+?> regular expression with the /s option enabled so it will match
790 all characters. By default it will be a non-greedy grab but you can
791 change that in the constructor by enabling the C<greedy_chunk> option.
792
793     [%Start FOO%]
794         [% START bar %]
795                 [% field %]
796         [% end bar %]
797     [%End FOO%]
798
799 =head2 Includes
800
801 =head1 RENDERING RULES
802
803 Template::Simple has a short list of rendering rules and they are easy
804 to understand. There are two types of renderings, include rendering
805 and chunk rendering. In the C<render> method, the template is an
806 unnamed top level chunk of text and it first gets its C<INCLUDE>
807 markups rendered. The text then undergoes a chunk rendering and a
808 scalar reference to that rendered template is returned to the caller.
809
810 =head2 Include Rendering
811
812 Include rendering is performed one time on a top level template. When
813 it is done the template is ready for chunk rendering.  Any markup of
814 the form C<[%INCLUDE name]%> will be replaced by the text found in the
815 template C<name>. The template name is looked up in the object's
816 template cache and if it is found there its text is used as the
817 replacement.
818
819 If a template is not found in the cache, it will be searched for in
820 the list of directories in the C<include_paths> option. The file name
821 will be a directory in that list appended with the template name and
822 the C<.tmpl> suffix. The first template file found will be read in and
823 stored in the cache. Its path is also saved and those will be returned
824 in the C<get_dependencies> method. See the C<add_templates> and
825 C<delete_templates> methods and the C<include_paths> option.
826
827 Rendered include text can contain more C<INCLUDE> markups and they
828 will also be rendered. The include rendering phase ends where there
829 are no more C<INCLUDE> found.
830
831 =head2 Chunk Rendering
832
833 A chunk is the text found between C<START> and C<END> markups and it
834 gets its named from the C<START> markup. The top level template is
835 considered an unamed chunk and also gets chunk rendered.
836
837 The data for a chunk determines how it will be rendered. The data can
838 be a scalar or scalar reference or an array, hash or code
839 reference. Since chunks can contain nested chunks, rendering will
840 recurse down the data tree as it renders the chunks.  Each of these
841 renderings are explained below. Also see the IDIOMS and BEST PRACTICES
842 section for examples and used of these renderings.
843
844 =head2 Scalar Data Rendering
845
846 If the current data for a chunk is a scalar or scalar reference, the
847 chunk's text in the templated is replaced by the scalar's value. This
848 can be used to overwrite one default section of text with from the
849 data tree.
850
851 =head2 Code Data Rendering
852
853 If the current data for a chunk is a code reference (also called
854 anonymous sub) then the code reference is called and it is passed a
855 scalar reference to the that chunk's text. The code must return a
856 scalar or a scalar reference and its value replaces the chunk's text
857 in the template. If the code returns any other type of data it is a
858 fatal error. Code rendering is how you can do custom renderings and
859 plugins. A key idiom is to use closures as the data in code renderings
860 and keep the required outside data in the closure.
861
862 =head2 Array Data Rendering
863
864 If the current data for a chunk is an array reference do a full chunk
865 rendering for each value in the array. It will replace the original
866 chunk text with the joined list of rendered chunks. This is how you do
867 repeated sections in Template::Simple and why there is no need for any
868 loop markups. Note that this means that rendering a chunk with $data
869 and [ $data ] will do the exact same thing. A value of an empty array
870 C<[]> will cause the chunk to be replaced by the empty string.
871
872 =head2 Hash Data Rendering
873
874 If the current data for a chunk is a hash reference then two phases of
875 rendering happen, nested chunk rendering and token rendering. First
876 nested chunks are parsed of of this chunk along with their names. Each
877 parsed out chunk is rendered based on the value in the current hash
878 with the nested chunk's name as the key.
879
880 If a value is not found (undefined), then the nested chunk is replaced
881 by the empty string. Otherwise the nested chunk is rendered according
882 to the type of its data (see chunk rendering) and it is replaced by
883 the rendered text.
884
885 Chunk name and token lookup in the hash data is case sensitive (see
886 the TODO for cased lookups).
887
888 Note that to keep a plain text chunk or to just have the all of its
889 markups (chunks and tokens) be deleted just pass in an empty hash
890 reference C<{}> as the data for the chunk. It will be rendered but all
891 markups will be replaced by the empty string.
892
893 =head2 Token Rendering
894
895 The second phase is token rendering. Markups of the form [%token%] are
896 replaced by the value of the hash element with the token as the
897 key. If a token's value is not defined it is replaced by the empty
898 string. This means if a token key is missing in the hash or its value
899 is undefined or its value is the empty string, the [%token%] markup
900 will be deleted in the rendering.
901
902 =head1 IDIOMS and BEST PRACTICES
903
904 With all template systems there are better ways to do things and
905 Template::Simple is no different. This section will show some ways to
906 handle typical template needs while using only the 4 markups in this
907 module. 
908
909 =head2 Conditionals
910
911 This conditional idiom can be when building a fresh data tree or
912 modifying an existing one.
913
914         $href->{$chunk_name} = $keep_chunk ? {} : '' ;
915
916 If you are building a fresh data tree you can use this idiom to do a
917 conditional chunk:
918
919         $href->{$chunk_name} = {} if $keep_chunk ;
920
921 To handle an if/else conditional use two chunks, with the else chunk's
922 name prefixed with NOT_ (or use any name munging you want). Then you
923 set the data for either the true chunk (just the plain name) or the
924 false trunk with the NOT_ name. You can use a different name for the
925 else chunk if you want but keeping the names of the if/else chunks
926 related is a good idea. Here are two ways to set the if/else data. The
927 first one uses the same data for both the if and else chunks and the
928 second one uses different data so the it uses the full if/else code
929 for that.
930
931         $href->{ ($boolean ? '' : 'NOT_') . $chunk_name} = $data
932
933         if ( $boolean ) {
934                 $href->{ $chunk_name} = $true_data ;
935         else {
936                 $href->{ "NOT_$chunk_name" } = $false_data ;
937         }
938
939 NOTE TO ALPHA USERS: i am also thinking that a non-existing key or
940 undefined hash value should leave the chunk as is. then you would need
941 to explicitly replace a chunk with the empty string if you wanted it
942 deleted.  It does affect the list of styles idiom. Any thoughts on
943 this change of behavior? Since this hasn't been released it is the
944 time to decide this.
945
946 =head2 Chunked Includes
947
948 One of the benefits of using include templates is the ability to share
949 and reuse existing work. But if an included template has a top level
950 named chunk, then that name would also be the same everywhere where
951 this template is included. If a template included another template in
952 multiple places, its data tree would use the same name for each and
953 not allow unique data to be rendered for each include. A better way is
954 to have the current template wrap an include markup in a named chunk
955 markup. Then the data tree could use unique names for each included
956 template. Here is how it would look:
957
958         [%START foo_prime%][%INCLUDE foo%][%START foo_prime%]
959         random noise
960         [%START foo_second%][%INCLUDE foo%][%START foo_second%]
961
962 See the TODO section for some ideas on how to make this even more high level.
963
964 =head2 Repeated Sections
965
966 If you looked at the markup of Template::Simple you have noticed that
967 there is no loop or repeat construct. That is because there is no need
968 for one. Any chunk can be rendered in a loop just by having its
969 rendering data be an anonymous array. The renderer will loop over each
970 element of the array and do a fresh rendering of the chunk with this
971 data. A join (on '') of the list of renderings replaces the original
972 chunk and you have a repeated chunk.
973
974 =head2 A List of Mixed Styles
975
976 One formating style is to have a list of sections each which can have
977 its own style or content. Template::Simple can do this very easily
978 with just a 2 level nested chunk and an array of data for
979 rendering. The outer chunk includes (or contains) each of the desired
980 styles in any order. It looks like this:
981
982         [%START para_styles%]
983                 [%START main_style%]
984                         [%INCLUDE para_style_main%]
985                 [%END main_style%]
986                 [%START sub_style%]
987                         [%INCLUDE para_style_sub%]
988                 [%END sub_style%]
989                 [%START footer_style%]
990                         [%INCLUDE para_style_footer%]
991                 [%END footer_style%]
992         [%END para_styles%]
993
994 The other part to make this work is in the data tree. The data for
995 para_styles should be a list of hashes. Each hash contains the data
996 for one pargraph style which is keyed by the style's chunk name. Since
997 the other styles's chunk names are not hash they are deleted. Only the
998 style which has its name as a key in the hash is rendered. The data
999 tree would look something like this:
1000
1001         [
1002                 {
1003                         main_style => $main_data,
1004                 },
1005                 {
1006                         sub_style => $sub_data,
1007                 },
1008                 {
1009                         sub_style => $other_sub_data,
1010                 },
1011                 {
1012                         footer_style => $footer_data,
1013                 },
1014         ]
1015
1016 =head1 TESTS
1017
1018 The test scripts use a common test driver module in t/common.pl. It is
1019 passed a list of hashes, each of which has the data for one test. A
1020 test can create a ne Template::Simple object or use the one from the
1021 previous test. The template source, the data tree and the expected
1022 results are also important keys. See the test scripts for examples of
1023 how to write tests using this common driver.
1024
1025 =over 4
1026
1027 =item name
1028
1029 This is the name of the test and is used by Test::More
1030
1031 =item opts
1032
1033 This is a hash ref of the options passed to the Template::Simple
1034 constructor.  The object is not built if the C<keep_obj> key is set.
1035
1036 =item keep_obj
1037
1038 If set, this will make this test keep the Template::Simple object from
1039 the previous test and not build a new one.
1040
1041 =item template
1042
1043 This is the template to render for this test. If not set, the test
1044 driver will use the template from the previous test. This is useful to
1045 run a series of test variants with the same template.
1046
1047 =item data
1048
1049 This is the data tree for the rendering of the template.
1050
1051 =item expected
1052
1053 This is the text that is expected after the rendering.
1054
1055 =item skip
1056
1057 If set, this test is skipped.
1058
1059 =back
1060
1061 =head1 TODO
1062
1063 Even though this template system is simple, that doesn't mean it can't
1064 be extended in many ways. Here are some features and designs that
1065 would be good extensions which add useful functionality without adding
1066 too much complexity.
1067
1068 =head2 Compiled Templates
1069
1070 A commonly performed optimization in template modules is to precompile
1071 (really preparse) templates into a internal form that will render
1072 faster.  Precompiling is slower than rendering from the original
1073 template which means you won't want to do it for each rendering. This
1074 means it has a downside that you lose out when you want to render
1075 using templates which change often. Template::Simple makes it very
1076 easy to precompile as it already has the regexes to parse out the
1077 markup. So instead of calling subs to do actual rendering, a
1078 precompiler would call subs to generate a compiled rendering tree.
1079 The rendering tree can then be run or processes with rendering data
1080 passed to it. You can think of a precompiled template as having all
1081 the nested chunks be replaced by nested code that does the same
1082 rendering. It can still do the dynamic rendering of the data but it
1083 saves the time of parsing the template souice. There are three
1084 possible internal formats for the precompiled template:
1085
1086 =over 4
1087
1088 =item Source code
1089
1090 This precompiler will generate source code that can be stored and/or
1091 eval'ed.  The eval'ed top level sub can then be called and passed the
1092 rendering data.
1093
1094 =item Closure call tree
1095
1096 The internal format can be a nested set of closures. Each closure would contain
1097 private data such as fixed text parts of the original template, lists
1098 of other closures to run, etc. It is trivial to write a basic closure
1099 generator which will make build this tree a simple task. 
1100
1101 =item Code ref call tree
1102
1103 This format is a Perl data tree where the nodes have a code reference
1104 and its args (which can be nested instances of the same
1105 nodes). Instead of executing this directly, you will need a small
1106 interpreter to execute all the code refs as it runs through the tree.
1107
1108 This would make for a challenging project to any intermediate Perl
1109 hacker. It just involves knowing recursion, data trees and code refs.
1110 Contact me if you are interested in doing this.
1111
1112 =back
1113
1114 =head2 Cased Hash Lookups
1115
1116 One possible option is to allow hash renderings to always use upper or
1117 lower cased keys in their lookups.
1118
1119 =head2 Render tokens before includes and chunks
1120
1121 Currently tokens are rendered after includes and chunks. If tokens
1122 were rendered in a pass before the others, the include and chunk names
1123 could be dynamically set. This would make it harder to precompile
1124 templates as too much would be dynamic, i.e. you won't know what the
1125 fixed text to parse out is since anything can be included at render
1126 time. But the extra flexibility of changing the include and chunk
1127 names would be interesting. It could be done easily and enabled by an
1128 option.
1129
1130 =head2 Plugins
1131
1132 There are two different potential areas in Template::Simple that could
1133 use plugins. The first is with the rendering of chunkas and
1134 dispatching based on the data type. This dispatch table can easily be
1135 replaced by loaded modules which offer a different way to
1136 render. These include the precompiled renderers mentioned above. The
1137 other area is with code references as the data type. By defining a
1138 closure (or a closure making) API you can create different code refs
1139 for the rendering data. The range of plugins is endless some of the
1140 major template modules have noticed. One idea is to make a closure
1141 which contains a different Template::Simple object than the current
1142 one. This will allow rendering of a nested chunk with different rules
1143 than the current chunk being rendered.
1144
1145 =head2 Data Escaping
1146
1147 Some templaters have options to properly escape data for some types of
1148 text files such as html. this can be done with some variant of the
1149 _render_hash routine which also does the scalar rendering (which is
1150 where data is rendered). The rendering scalars code could be factored
1151 out into a set of subs one of which is used based on any escaping
1152 needs.
1153
1154 =head2 Data Tree is an Object
1155
1156 This is a concept I don't like but it was requested so it goes into
1157 the TODO file. Currently C<render> can only be passed a regular
1158 (unblessed) ref (or a scalar) for its data tree. Passing in an object
1159 would break encapsulation and force the object layout to be a hash
1160 tree that matches the layout of the template. I doubt that most
1161 objects will want to be organized to match a template. I have two
1162 ideas, one is that you add a method to that object that builds up a
1163 proper (unblessed) data tree to pass to C<render>. The other is by
1164 subclassing C<Template::Simple> and overriding C<render> with a sub
1165 that does take an object hash and it can unbless it or build a proper
1166 data tree and then call C<render> in SUPER::. A quick solution is to
1167 use C<reftype> (from Scalar::Utils) instead of C<ref> to allow object
1168 hashes to be passed in.
1169
1170 =head2 Includes and Closure Synergy
1171
1172 By pairing up an include template along with code that can generate
1173 the appropriate data tree for its rendering, you can create a higher
1174 level template framework (the synergy). Additional code can be
1175 associated with them that will handle input processing and
1176 verification for the templates (e.g. web forms) that need it. A key to
1177 this will be making all the closures for the data tree. This can be
1178 greatly simplified by using a closure maker sub that can create all
1179 the required closures.
1180
1181 =head2 Metafields and UI Generation
1182
1183 Taking the synergy up to a much higher level is the concept of meta
1184 knowledge of fields which can generate templates, output processing
1185 (data tree generation), input processing, DB backing and more. If you
1186 want to discuss such grandiose wacky application schemes in a long
1187 rambling mind bending conversation, please contact me.
1188
1189 =head2 More Examples and Idioms
1190
1191 As I convert several scripts over to this module (they all used the
1192 hack version), I will add them to an examples section or possibly put
1193 them in another (pod only) module. Similarly the Idioms section needs
1194 rendering and could be also put into a pod module. One goal requested
1195 by an early alpha tester is to keep the primary docs as simple as the
1196 markup itself. This means moving all the extra stuff (and plenty of
1197 that) into other pod modules. All the pod modules would be in the same
1198 cpan tarball so you get all the docs and examples when you install
1199 this.
1200
1201 =head1 AUTHOR
1202
1203 Uri Guttman, C<< <uri at sysarch.com> >>
1204
1205 =head1 BUGS
1206
1207 Please report any bugs or feature requests to
1208 C<bug-template-simple at rt.cpan.org>, or through the web interface at
1209 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Template-Simple>.
1210 I will be notified, and then you'll automatically be notified of progress on
1211 your bug as I make changes.
1212
1213 =head1 SUPPORT
1214
1215 You can find documentation for this module with the perldoc command.
1216
1217     perldoc Template::Simple
1218
1219 You can also look for information at:
1220
1221 =over 4
1222
1223 =item * RT: CPAN's request tracker
1224
1225 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Template-Simple>
1226
1227 =item * Search CPAN
1228
1229 L<http://search.cpan.org/dist/Template-Simple>
1230
1231 =back
1232
1233 =head1 ACKNOWLEDGEMENTS
1234
1235 I wish to thank Turbo10 for their support in developing this module.
1236
1237 =head1 COPYRIGHT & LICENSE
1238
1239 Copyright 2006 Uri Guttman, all rights reserved.
1240
1241 This program is free software; you can redistribute it and/or modify it
1242 under the same terms as Perl itself.
1243
1244 =cut
1245
1246
1247 find templates and tests
1248
1249 deep nesting tests
1250
1251 greedy tests
1252
1253 methods pod
1254
1255 delete_templates test
1256
1257 pod cleanup
1258
1259 fine edit
1260
1261 more tests
1262
1263 slurp dependency in makefile.pl
1264