1 package Template::Simple;
8 use Scalar::Util qw( reftype ) ;
12 our $VERSION = '0.03';
17 post_delim => qr/%\]/,
21 include_paths => [ qw( templates ) ],
26 my( $class, %opts ) = @_ ;
28 my $self = bless {}, $class ;
30 # get all the options or defaults into the object
32 while( my( $name, $default ) = each %opt_defaults ) {
34 $self->{$name} = defined( $opts{$name} ) ?
35 $opts{$name} : $default ;
38 # make up the regexes to parse the markup from templates
40 # this matches scalar markups and grabs the name
42 $self->{scalar_re} = qr{
44 \s* # optional leading whitespace
45 (\w+?) # grab scalar name
46 \s* # optional trailing whitespace
48 }xi ; # case insensitive
50 #print "RE <$self->{scalar_re}>\n" ;
52 # this grabs the body of a chunk in either greedy or non-greedy modes
54 my $chunk_body = $self->{greedy_chunk} ? qr/.+/s : qr/.+?/s ;
56 # this matches a marked chunk and grabs its name and text body
58 $self->{chunk_re} = qr{
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
66 ($chunk_body) # grab the chunk body
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
74 }xi ; # case insensitive
76 #print "RE <$self->{chunk_re}>\n" ;
78 # this matches a include markup and grabs its template name
80 $self->{include_re} = qr{
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
88 }xi ; # case insensitive
90 # load in any templates
92 $self->add_templates( $opts{templates} ) ;
99 my( $self, $template_name ) = @_ ;
101 my $tmpl_ref = eval {
102 $self->_get_template( $template_name ) ;
105 croak "Template::Simple $@" if $@ ;
107 # compile a copy of the template as it will be destroyed
109 my $code_body = $self->_compile_chunk( '', "${$tmpl_ref}", "\t" ) ;
111 my $source = <<CODE ;
126 my $code_ref = eval $source ;
130 $self->{compiled_cache}{$template_name} = $code_ref ;
131 $self->{source_cache}{$template_name} = $source ;
136 my( $self, $chunk_name, $template, $indent ) = @_ ;
138 return '' unless length $template ;
140 # generate a lookup in data for this chunk name (unless it is the top
141 # level). this descends down the data tree during rendering
143 my $data_init = $chunk_name ? "\$data->{$chunk_name}" : '$data' ;
146 ${indent}my \@data = $data_init ;
147 ${indent}while( defined( my \$data = shift \@data ) ) {
149 ${indent} if ( ref \$data eq 'ARRAY' ) {
150 ${indent} push \@data, \@{\$data} ;
158 # loop all nested chunks and the text separating them
160 while( $template =~ m{$self->{chunk_re}} ) {
162 # get the pre-match text and compile its scalars and text. append to the code
164 $code .= $self->_compile_scalars(
165 substr( $template, 0, $-[0] ), $indent ) ;
167 # print "OFF: $-[0] $+[0]\n" ;
168 # print "PRE: [", substr( $template, 0, $-[0] ), "]\n\n" ;
169 # print "CHUNK: [$1] BODY [$2]\n\n" ;
170 # print "TRUNC: [", substr( $template, 0, $+[0] ), "]\n\n" ;
171 # print "LEFT: [$template]\n\n" ;
173 # compile the nested chunk and append to the code
175 $code .= $self->_compile_chunk( $1, $2, $indent ) ;
177 # chop off the pre-match and the chunk
179 substr( $template, 0, $+[0], '' ) ;
182 # compile trailing text for scalars and append to the code
184 $code .= $self->_compile_scalars( $template, $indent ) ;
188 # now we end the loop for this chunk
196 sub _compile_scalars {
198 my( $self, $template, $indent ) = @_ ;
200 # if the template is empty return no parts
202 return '' unless length $template ;
206 while( $template =~ m{$self->{scalar_re}}g ) {
208 # get the pre-match text before the scalar markup and generate code to
212 dump_text( substr( $template, 0, $-[0] ) ),
216 # truncate the matched text so the next match starts at begining of string
218 substr( $template, 0, $+[0], '' ) ;
221 # keep any trailing text part
223 push @parts, dump_text( $template ) ;
225 my $parts_code = join( "\n$indent.\n$indent", @parts ) ;
229 ${indent}\$out .= ref \$data ne 'HASH' ? \$data :
230 ${indent}$parts_code ;
240 return unless length $text ;
242 local( $Data::Dumper::Useqq ) = 1 ;
244 my $dumped = Dumper $text ;
246 $dumped =~ s/^[^"]+// ;
247 $dumped =~ s/;\n$// ;
254 my( $self, $template_name ) = @_ ;
256 return $self->{source_cache}{$template_name} ;
261 my( $self, $template_name, $data ) = @_ ;
263 my $tmpl_ref = ref $template_name eq 'SCALAR' ? $template_name : '' ;
265 unless( $tmpl_ref ) {
267 # render with cached code and return if we precompiled this template
269 if ( my $compiled = $self->{compiled_cache}{$template_name} ) {
271 return $compiled->($data) ;
274 # not compiled so get this template by name
276 $tmpl_ref ||= eval{ $self->_get_template($template_name) } ;
278 # we couldn't find this template name so assume it is the template text
280 $tmpl_ref ||= \$template_name ;
283 my $rendered = $self->_render_includes( $tmpl_ref ) ;
285 #print "INC EXP <$rendered>\n" ;
288 $self->_render_chunk( $rendered, $data ) ;
291 croak "Template::Simple $@" if $@ ;
296 sub _render_includes {
298 my( $self, $tmpl_ref ) = @_ ;
300 # make a copy of the initial template so we can render it.
302 my $rendered = ${$tmpl_ref} ;
304 # loop until we can render no more include markups
307 s{$self->{include_re}}
308 { ${ $self->_get_template($1) }
316 HASH => \&_render_hash,
317 ARRAY => \&_render_array,
318 CODE => \&_render_code,
319 # if no ref then data is a scalar so replace the template with just the data
320 '' => sub { \$_[2] },
326 my( $self, $tmpl_ref, $data ) = @_ ;
328 #print "T ref [$tmpl_ref] [$$tmpl_ref]\n" ;
329 #print "CHUNK ref [$tmpl_ref] TMPL\n<$$tmpl_ref>\n" ;
331 #print Dumper $data ;
333 return \'' unless defined $data ;
335 # now render this chunk based on the type of data
337 my $renderer = $renderers{reftype $data || ''} ;
339 #print "EXP $renderer\nREF ", reftype $data, "\n" ;
341 die "unknown template data type '$data'\n" unless defined $renderer ;
343 return $self->$renderer( $tmpl_ref, $data ) ;
348 my( $self, $tmpl_ref, $href ) = @_ ;
350 return $tmpl_ref unless keys %{$href} ;
352 # we need a local copy of the template to render
354 my $rendered = ${$tmpl_ref} ;
357 # recursively render all top level chunks in this chunk
359 $rendered =~ s{$self->{chunk_re}}
361 # print "CHUNK $1\nBODY\n----\n<$2>\n\n------\n" ;
362 # print "CHUNK $1\nBODY\n----\n<$2>\n\n------\n" ;
363 # print "pre CHUNK [$`]\n" ;
364 ${ $self->_render_chunk( \"$2", $href->{$1} ) }
369 #print "HREF: ", Dumper $href ;
371 $rendered =~ s{$self->{scalar_re}}
373 # print "SCALAR $1 VAL $href->{$1}\n" ;
374 defined $href->{$1} ? $href->{$1} : ''
377 #print "HASH REND3\n<$rendered>\n" ;
384 my( $self, $tmpl_ref, $aref ) = @_ ;
386 # render this $tmpl_ref for each element of the aref and join them
390 #print "AREF: ", Dumper $aref ;
392 $rendered .= ${$self->_render_chunk( $tmpl_ref, $_ )} for @{$aref} ;
399 my( $self, $tmpl_ref, $cref ) = @_ ;
401 my $rendered = $cref->( $tmpl_ref ) ;
403 die <<DIE if ref $rendered ne 'SCALAR' ;
404 data callback to code didn't return a scalar or scalar reference
412 my( $self, $tmpls ) = @_ ;
414 #print Dumper $tmpls ;
415 return unless defined $tmpls ;
417 ref $tmpls eq 'HASH' or croak "templates argument is not a hash ref" ;
419 # copy all the templates from the arg hash and force the values to be
422 @{ $self->{tmpl_cache}}{ keys %{$tmpls} } =
423 map ref $_ eq 'SCALAR' ? \"${$_}" : \"$_", values %{$tmpls} ;
425 #print Dumper $self->{tmpl_cache} ;
430 sub delete_templates {
432 my( $self, @names ) = @_ ;
434 # delete all the cached stuff or just the names passed in
436 @names = keys %{$self->{tmpl_cache}} unless @names ;
438 # clear out all the caches
439 # TODO: reorg these into a hash per name
441 delete @{$self->{tmpl_cache}}{ @names } ;
442 delete @{$self->{compiled_cache}}{ @names } ;
443 delete @{$self->{source_cache}}{ @names } ;
445 # also remove where we found it to force a fresh search
447 delete @{$self->{template_paths}}{ @names } ;
454 my( $self, $tmpl_name ) = @_ ;
456 #print "INC $tmpl_name\n" ;
458 my $tmpls = $self->{tmpl_cache} ;
460 # get the template from the cache and send it back if it was found there
462 my $template = $tmpls->{ $tmpl_name } ;
463 return $template if $template ;
465 # not found, so find, slurp in and cache the template
467 $template = $self->_find_template( $tmpl_name ) ;
468 $tmpls->{ $tmpl_name } = $template ;
475 my( $self, $tmpl_name ) = @_ ;
477 foreach my $dir ( @{$self->{include_paths}} ) {
479 my $tmpl_path = "$dir/$tmpl_name.tmpl" ;
481 #print "PATH: $tmpl_path\n" ;
482 next unless -r $tmpl_path ;
484 # cache the path to this template
486 $self->{template_paths}{$tmpl_name} = $tmpl_path ;
488 # slurp in the template file and return it as a scalar ref
490 return scalar read_file( $tmpl_path, scalar_ref => 1 ) ;
494 can't find template '$tmpl_name' in '@{$self->{include_paths}}'
499 1; # End of Template::Simple
505 Template::Simple - A simple and fast template module
513 use Template::Simple;
515 my $tmpl = Template::Simple->new();
517 my $template = <<TMPL ;
520 [%first%] - [%second%]
527 date => 'Jan 1, 2008',
528 author => 'Me, myself and I',
532 first => 'row 1 value 1',
533 second => 'row 1 value 2',
536 first => 'row 2 value 1',
537 second => 'row 2 value 2',
541 modified => 'Aug 31, 2006',
545 my $rendered = $tmpl->render( $template, $data ) ;
549 Template::Simple has these goals:
553 =item * Support most common template operations
555 It can recursively include other templates, replace tokens (scalars),
556 recursively render nested chunks of text and render lists. By using
557 simple idioms you can get conditional renderings.
559 =item * Complete isolation of template from program code
561 This is very important as template design can be done by different
562 people than the program logic. It is rare that one person is well
563 skilled in both template design and also programming.
565 =item * Very simple template markup (only 4 markups)
567 The only markups are C<INCLUDE>, C<START>, C<END> and C<token>. See
570 =item * Easy to follow rendering rules
572 Rendering of templates and chunks is driven from a data tree. The type
573 of the data element used in an rendering controls how the rendering
574 happens. The data element can be a scalar or scalar reference or an
575 array, hash or code reference.
577 =item * Efficient template rendering
579 Rendering is very simple and uses Perl's regular expressions
580 efficiently. Because the markup is so simple less processing is needed
581 than many other templaters. Precompiling templates is not supported
582 yet but that optimization is on the TODO list.
584 =item * Easy user extensions
586 User code can be called during an rendering so you can do custom
587 renderings and plugins. Closures can be used so the code can have its
588 own private data for use in rendering its template chunk.
594 You create a Template::Simple by calling the class method new:
596 my $tmpl = Template::Simple->new() ;
598 All the arguments to C<new()> are key/value options that change how
599 the object will do renderings.
605 This option sets the string or regex that is the starting delimiter
606 for all markups. You can use a plain string or a qr// but you need to
607 escape (with \Q or \) any regex metachars if you want them to be plain
608 chars. The default is qr/\[%/.
610 my $tmpl = Template::Simple->new(
614 my $rendered = $tmpl->render( '<%FOO%]', 'bar' ) ;
618 This option sets the string or regex that is the ending delimiter
619 for all markups. You can use a plain string or a qr// but you need to
620 escape (with \Q or \) any regex metachars if you want them to be plain
621 chars. The default is qr/%]/.
623 my $tmpl = Template::Simple->new(
627 my $rendered = $tmpl->render( '[%FOO%>', 'bar' ) ;
631 This boolean option will cause the regex that grabs a chunk of text
632 between the C<START/END> markups to become greedy (.+). The default is
633 a not-greedy grab of the chunk text. (UNTESTED)
637 This option lets you load templates directly into the cache of the
638 Template::Simple object. This cache will be searched by the C<INCLUDE>
639 markup which will be replaced by the template if found. The option
640 value is a hash reference which has template names (the name in the
641 C<INCLUDE> markup) for keys and their template text as their
642 values. You can delete or clear templates from the object cache with
643 the C<delete_template> method.
646 my $tmpl = Template::Simple->new(
650 [%baz%] is a [%quux%]
653 [%user%] is not a [%fool%]
658 my $template = <<TMPL ;
662 my $rendered = $tmpl->render(
672 Template::Simple can also load C<INCLUDE> templates from files. This
673 option lets you set the directory paths to search for those
674 files. Note that the template name in the C<INCLUDE> markup has the
675 .tmpl suffix appended to it when searched for in one of these
676 paths. The loaded file is cached inside the Template::Simple object
677 along with any loaded by the C<templates> option.
685 This method is passed a template and a data tree and it renders it and
686 returns a reference to the resulting string. The template argument can
687 be a scalar or a scalar reference. The data tree argument can be any
688 value allowed by Template::Simple when rendering a template. It can
689 also be a blessed reference (Perl object) since
690 C<Scalar::Util::reftype> is used instead of C<ref> to determine the
693 Note that the author recommends against passing in an object as this
694 breaks encapsulation and forces your object to be (most likely) a
695 hash. It would be better to create a simple method that copies the
696 object contents to a hash reference and pass that. But current
697 templaters allow passing in objects so that is supported here as well.
699 my $rendered = $tmpl->render( $template, $data ) ;
703 This method adds templates to the object cache. It takes a list of template names and texts just like the C<templates> constructor option.
705 $tmpl->add_templates(
707 foo => \$foo_template,
708 bar => '[%include bar%]',
712 =head2 delete_templates
714 This method takes a list of template names and will delete them from
715 the template cache in the object. If you pass in an empty list then
716 all the templates will be deleted. This can be used when you know a
717 template file has been updated and you want to get it loaded back into
718 the cache. Note that you can delete templates that were loaded
719 directly (via the C<templates> constructor option or the
720 C<add_templates> method) or loaded from a file.
722 # this deletes only the foo and bar templates from the object cache
724 $tmpl->delete_templates( qw( foo bar ) ;
726 # this deletes all of templates from the object cache
728 $tmpl->delete_templates() ;
730 =head2 get_dependencies
732 This method render the only C<INCLUDE> markups of a template and it
733 returns a list of the file paths that were found and loaded. It is
734 meant to be used to build up a dependency list of included templates
735 for a main template. Typically this can be called from a script (see
736 TODO) that will do this for a set of main templates and will generate
737 Makefile dependencies for them. Then you can regenerate rendered
738 templates only when any of their included templates have changed. It
739 takes a single argument of a template.
741 UNKNOWN: will this require a clearing of the cache or will it do the
742 right thing on its own? or will it use the file path cache?
745 $tmpl->get_dependencies( '[%INCLUDE top_level%]' );
749 All the markups in Template::Simple use the same delimiters which are
750 C<[%> and C<%]>. You can change the delimiters with the C<pre_delim>
751 and C<post_delim> options in the C<new()> constructor.
755 A token is a single markup with a C<\w+> Perl word inside. The token
756 can have optional whitespace before and after it. A token is replaced
757 by a value looked up in a hash with the token as the key. The hash
758 lookup keeps the same case as parsed from the token markup.
762 Those will be replaced by C<$href->{foo}> and C<$href->{BAR}> assuming
763 C<$href> is the current data for this rendering. Tokens are only
764 parsed out during hash data rendering so see Hash Data for more.
768 Chunks are regions of text in a template that are marked off with a
769 start and end markers with the same name. A chunk start marker is
770 C<[%START name%]> and the end marker for that chunk is C<[%END
771 name%]>. C<name> is a C<\w+> Perl word which is the name of this
772 chunk. The whitespace between C<START/END> and C<name> is required and
773 there is optional whitespace before C<START/END> and after the
774 C<name>. C<START/END> are case insensitive but the C<name>'s case is
775 kept. C<name> must match in the C<START/END> pair and it used as a key
776 in a hash data rendering. Chunks are the primary way to markup
777 templates for structures (sets of tokens), nesting (hashes of hashes),
778 repeats (array references) and callbacks to user code. Chunks are only
779 parsed out during hash data rendering so see Hash Data for more.
781 The body of text between the C<START/END> markups is grabbed with a
782 C<.+?> regular expression with the /s option enabled so it will match
783 all characters. By default it will be a non-greedy grab but you can
784 change that in the constructor by enabling the C<greedy_chunk> option.
794 =head1 RENDERING RULES
796 Template::Simple has a short list of rendering rules and they are easy
797 to understand. There are two types of renderings, include rendering
798 and chunk rendering. In the C<render> method, the template is an
799 unnamed top level chunk of text and it first gets its C<INCLUDE>
800 markups rendered. The text then undergoes a chunk rendering and a
801 scalar reference to that rendered template is returned to the caller.
803 =head2 Include Rendering
805 Include rendering is performed one time on a top level template. When
806 it is done the template is ready for chunk rendering. Any markup of
807 the form C<[%INCLUDE name]%> will be replaced by the text found in the
808 template C<name>. The template name is looked up in the object's
809 template cache and if it is found there its text is used as the
812 If a template is not found in the cache, it will be searched for in
813 the list of directories in the C<include_paths> option. The file name
814 will be a directory in that list appended with the template name and
815 the C<.tmpl> suffix. The first template file found will be read in and
816 stored in the cache. Its path is also saved and those will be returned
817 in the C<get_dependencies> method. See the C<add_templates> and
818 C<delete_templates> methods and the C<include_paths> option.
820 Rendered include text can contain more C<INCLUDE> markups and they
821 will also be rendered. The include rendering phase ends where there
822 are no more C<INCLUDE> found.
824 =head2 Chunk Rendering
826 A chunk is the text found between C<START> and C<END> markups and it
827 gets its named from the C<START> markup. The top level template is
828 considered an unamed chunk and also gets chunk rendered.
830 The data for a chunk determines how it will be rendered. The data can
831 be a scalar or scalar reference or an array, hash or code
832 reference. Since chunks can contain nested chunks, rendering will
833 recurse down the data tree as it renders the chunks. Each of these
834 renderings are explained below. Also see the IDIOMS and BEST PRACTICES
835 section for examples and used of these renderings.
837 =head2 Scalar Data Rendering
839 If the current data for a chunk is a scalar or scalar reference, the
840 chunk's text in the templated is replaced by the scalar's value. This
841 can be used to overwrite one default section of text with from the
844 =head2 Code Data Rendering
846 If the current data for a chunk is a code reference (also called
847 anonymous sub) then the code reference is called and it is passed a
848 scalar reference to the that chunk's text. The code must return a
849 scalar or a scalar reference and its value replaces the chunk's text
850 in the template. If the code returns any other type of data it is a
851 fatal error. Code rendering is how you can do custom renderings and
852 plugins. A key idiom is to use closures as the data in code renderings
853 and keep the required outside data in the closure.
855 =head2 Array Data Rendering
857 If the current data for a chunk is an array reference do a full chunk
858 rendering for each value in the array. It will replace the original
859 chunk text with the joined list of rendered chunks. This is how you do
860 repeated sections in Template::Simple and why there is no need for any
861 loop markups. Note that this means that rendering a chunk with $data
862 and [ $data ] will do the exact same thing. A value of an empty array
863 C<[]> will cause the chunk to be replaced by the empty string.
865 =head2 Hash Data Rendering
867 If the current data for a chunk is a hash reference then two phases of
868 rendering happen, nested chunk rendering and token rendering. First
869 nested chunks are parsed of of this chunk along with their names. Each
870 parsed out chunk is rendered based on the value in the current hash
871 with the nested chunk's name as the key.
873 If a value is not found (undefined), then the nested chunk is replaced
874 by the empty string. Otherwise the nested chunk is rendered according
875 to the type of its data (see chunk rendering) and it is replaced by
878 Chunk name and token lookup in the hash data is case sensitive (see
879 the TODO for cased lookups).
881 Note that to keep a plain text chunk or to just have the all of its
882 markups (chunks and tokens) be deleted just pass in an empty hash
883 reference C<{}> as the data for the chunk. It will be rendered but all
884 markups will be replaced by the empty string.
886 =head2 Token Rendering
888 The second phase is token rendering. Markups of the form [%token%] are
889 replaced by the value of the hash element with the token as the
890 key. If a token's value is not defined it is replaced by the empty
891 string. This means if a token key is missing in the hash or its value
892 is undefined or its value is the empty string, the [%token%] markup
893 will be deleted in the rendering.
895 =head1 IDIOMS and BEST PRACTICES
897 With all template systems there are better ways to do things and
898 Template::Simple is no different. This section will show some ways to
899 handle typical template needs while using only the 4 markups in this
904 This conditional idiom can be when building a fresh data tree or
905 modifying an existing one.
907 $href->{$chunk_name} = $keep_chunk ? {} : '' ;
909 If you are building a fresh data tree you can use this idiom to do a
912 $href->{$chunk_name} = {} if $keep_chunk ;
914 To handle an if/else conditional use two chunks, with the else chunk's
915 name prefixed with NOT_ (or use any name munging you want). Then you
916 set the data for either the true chunk (just the plain name) or the
917 false trunk with the NOT_ name. You can use a different name for the
918 else chunk if you want but keeping the names of the if/else chunks
919 related is a good idea. Here are two ways to set the if/else data. The
920 first one uses the same data for both the if and else chunks and the
921 second one uses different data so the it uses the full if/else code
924 $href->{ ($boolean ? '' : 'NOT_') . $chunk_name} = $data
927 $href->{ $chunk_name} = $true_data ;
929 $href->{ "NOT_$chunk_name" } = $false_data ;
932 NOTE TO ALPHA USERS: i am also thinking that a non-existing key or
933 undefined hash value should leave the chunk as is. then you would need
934 to explicitly replace a chunk with the empty string if you wanted it
935 deleted. It does affect the list of styles idiom. Any thoughts on
936 this change of behavior? Since this hasn't been released it is the
939 =head2 Chunked Includes
941 One of the benefits of using include templates is the ability to share
942 and reuse existing work. But if an included template has a top level
943 named chunk, then that name would also be the same everywhere where
944 this template is included. If a template included another template in
945 multiple places, its data tree would use the same name for each and
946 not allow unique data to be rendered for each include. A better way is
947 to have the current template wrap an include markup in a named chunk
948 markup. Then the data tree could use unique names for each included
949 template. Here is how it would look:
951 [%START foo_prime%][%INCLUDE foo%][%START foo_prime%]
953 [%START foo_second%][%INCLUDE foo%][%START foo_second%]
955 See the TODO section for some ideas on how to make this even more high level.
957 =head2 Repeated Sections
959 If you looked at the markup of Template::Simple you have noticed that
960 there is no loop or repeat construct. That is because there is no need
961 for one. Any chunk can be rendered in a loop just by having its
962 rendering data be an anonymous array. The renderer will loop over each
963 element of the array and do a fresh rendering of the chunk with this
964 data. A join (on '') of the list of renderings replaces the original
965 chunk and you have a repeated chunk.
967 =head2 A List of Mixed Styles
969 One formating style is to have a list of sections each which can have
970 its own style or content. Template::Simple can do this very easily
971 with just a 2 level nested chunk and an array of data for
972 rendering. The outer chunk includes (or contains) each of the desired
973 styles in any order. It looks like this:
975 [%START para_styles%]
977 [%INCLUDE para_style_main%]
980 [%INCLUDE para_style_sub%]
982 [%START footer_style%]
983 [%INCLUDE para_style_footer%]
987 The other part to make this work is in the data tree. The data for
988 para_styles should be a list of hashes. Each hash contains the data
989 for one pargraph style which is keyed by the style's chunk name. Since
990 the other styles's chunk names are not hash they are deleted. Only the
991 style which has its name as a key in the hash is rendered. The data
992 tree would look something like this:
996 main_style => $main_data,
999 sub_style => $sub_data,
1002 sub_style => $other_sub_data,
1005 footer_style => $footer_data,
1011 The test scripts use a common test driver module in t/common.pl. It is
1012 passed a list of hashes, each of which has the data for one test. A
1013 test can create a ne Template::Simple object or use the one from the
1014 previous test. The template source, the data tree and the expected
1015 results are also important keys. See the test scripts for examples of
1016 how to write tests using this common driver.
1022 This is the name of the test and is used by Test::More
1026 This is a hash ref of the options passed to the Template::Simple
1027 constructor. The object is not built if the C<keep_obj> key is set.
1031 If set, this will make this test keep the Template::Simple object from
1032 the previous test and not build a new one.
1036 This is the template to render for this test. If not set, the test
1037 driver will use the template from the previous test. This is useful to
1038 run a series of test variants with the same template.
1042 This is the data tree for the rendering of the template.
1046 This is the text that is expected after the rendering.
1050 If set, this test is skipped.
1056 Even though this template system is simple, that doesn't mean it can't
1057 be extended in many ways. Here are some features and designs that
1058 would be good extensions which add useful functionality without adding
1059 too much complexity.
1061 =head2 Compiled Templates
1063 A commonly performed optimization in template modules is to precompile
1064 (really preparse) templates into a internal form that will render
1065 faster. Precompiling is slower than rendering from the original
1066 template which means you won't want to do it for each rendering. This
1067 means it has a downside that you lose out when you want to render
1068 using templates which change often. Template::Simple makes it very
1069 easy to precompile as it already has the regexes to parse out the
1070 markup. So instead of calling subs to do actual rendering, a
1071 precompiler would call subs to generate a compiled rendering tree.
1072 The rendering tree can then be run or processes with rendering data
1073 passed to it. You can think of a precompiled template as having all
1074 the nested chunks be replaced by nested code that does the same
1075 rendering. It can still do the dynamic rendering of the data but it
1076 saves the time of parsing the template souice. There are three
1077 possible internal formats for the precompiled template:
1083 This precompiler will generate source code that can be stored and/or
1084 eval'ed. The eval'ed top level sub can then be called and passed the
1087 =item Closure call tree
1089 The internal format can be a nested set of closures. Each closure would contain
1090 private data such as fixed text parts of the original template, lists
1091 of other closures to run, etc. It is trivial to write a basic closure
1092 generator which will make build this tree a simple task.
1094 =item Code ref call tree
1096 This format is a Perl data tree where the nodes have a code reference
1097 and its args (which can be nested instances of the same
1098 nodes). Instead of executing this directly, you will need a small
1099 interpreter to execute all the code refs as it runs through the tree.
1101 This would make for a challenging project to any intermediate Perl
1102 hacker. It just involves knowing recursion, data trees and code refs.
1103 Contact me if you are interested in doing this.
1107 =head2 Cased Hash Lookups
1109 One possible option is to allow hash renderings to always use upper or
1110 lower cased keys in their lookups.
1112 =head2 Render tokens before includes and chunks
1114 Currently tokens are rendered after includes and chunks. If tokens
1115 were rendered in a pass before the others, the include and chunk names
1116 could be dynamically set. This would make it harder to precompile
1117 templates as too much would be dynamic, i.e. you won't know what the
1118 fixed text to parse out is since anything can be included at render
1119 time. But the extra flexibility of changing the include and chunk
1120 names would be interesting. It could be done easily and enabled by an
1125 There are two different potential areas in Template::Simple that could
1126 use plugins. The first is with the rendering of chunkas and
1127 dispatching based on the data type. This dispatch table can easily be
1128 replaced by loaded modules which offer a different way to
1129 render. These include the precompiled renderers mentioned above. The
1130 other area is with code references as the data type. By defining a
1131 closure (or a closure making) API you can create different code refs
1132 for the rendering data. The range of plugins is endless some of the
1133 major template modules have noticed. One idea is to make a closure
1134 which contains a different Template::Simple object than the current
1135 one. This will allow rendering of a nested chunk with different rules
1136 than the current chunk being rendered.
1138 =head2 Data Escaping
1140 Some templaters have options to properly escape data for some types of
1141 text files such as html. this can be done with some variant of the
1142 _render_hash routine which also does the scalar rendering (which is
1143 where data is rendered). The rendering scalars code could be factored
1144 out into a set of subs one of which is used based on any escaping
1147 =head2 Data Tree is an Object
1149 This is a concept I don't like but it was requested so it goes into
1150 the TODO file. Currently C<render> can only be passed a regular
1151 (unblessed) ref (or a scalar) for its data tree. Passing in an object
1152 would break encapsulation and force the object layout to be a hash
1153 tree that matches the layout of the template. I doubt that most
1154 objects will want to be organized to match a template. I have two
1155 ideas, one is that you add a method to that object that builds up a
1156 proper (unblessed) data tree to pass to C<render>. The other is by
1157 subclassing C<Template::Simple> and overriding C<render> with a sub
1158 that does take an object hash and it can unbless it or build a proper
1159 data tree and then call C<render> in SUPER::. A quick solution is to
1160 use C<reftype> (from Scalar::Utils) instead of C<ref> to allow object
1161 hashes to be passed in.
1163 =head2 Includes and Closure Synergy
1165 By pairing up an include template along with code that can generate
1166 the appropriate data tree for its rendering, you can create a higher
1167 level template framework (the synergy). Additional code can be
1168 associated with them that will handle input processing and
1169 verification for the templates (e.g. web forms) that need it. A key to
1170 this will be making all the closures for the data tree. This can be
1171 greatly simplified by using a closure maker sub that can create all
1172 the required closures.
1174 =head2 Metafields and UI Generation
1176 Taking the synergy up to a much higher level is the concept of meta
1177 knowledge of fields which can generate templates, output processing
1178 (data tree generation), input processing, DB backing and more. If you
1179 want to discuss such grandiose wacky application schemes in a long
1180 rambling mind bending conversation, please contact me.
1182 =head2 More Examples and Idioms
1184 As I convert several scripts over to this module (they all used the
1185 hack version), I will add them to an examples section or possibly put
1186 them in another (pod only) module. Similarly the Idioms section needs
1187 rendering and could be also put into a pod module. One goal requested
1188 by an early alpha tester is to keep the primary docs as simple as the
1189 markup itself. This means moving all the extra stuff (and plenty of
1190 that) into other pod modules. All the pod modules would be in the same
1191 cpan tarball so you get all the docs and examples when you install
1196 Uri Guttman, C<< <uri at sysarch.com> >>
1200 Please report any bugs or feature requests to
1201 C<bug-template-simple at rt.cpan.org>, or through the web interface at
1202 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Template-Simple>.
1203 I will be notified, and then you'll automatically be notified of progress on
1204 your bug as I make changes.
1208 You can find documentation for this module with the perldoc command.
1210 perldoc Template::Simple
1212 You can also look for information at:
1216 =item * RT: CPAN's request tracker
1218 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Template-Simple>
1222 L<http://search.cpan.org/dist/Template-Simple>
1226 =head1 ACKNOWLEDGEMENTS
1228 I wish to thank Turbo10 for their support in developing this module.
1230 =head1 COPYRIGHT & LICENSE
1232 Copyright 2006 Uri Guttman, all rights reserved.
1234 This program is free software; you can redistribute it and/or modify it
1235 under the same terms as Perl itself.
1240 find templates and tests
1248 delete_templates test
1256 slurp dependency in makefile.pl