1 package Template::Simple;
7 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 $self->{source} = <<CODE ;
125 $self->{source_cache}{$template_name} = $self->{source} ;
126 print $self->{source} ;
128 my $code_ref = eval $self->{source} ;
132 $self->{compiled_cache}{$template_name} = $code_ref ;
138 my( $self, $chunk_name, $template, $indent ) = @_ ;
140 return '' unless length $template ;
146 # loop all nested chunks and the text separating them
148 while( $template =~ m{$self->{chunk_re}}g ) {
150 # grab the pre-chunk text and compile it for scalars and save all of its parts
152 push @parts, $self->_compile_scalars(
153 substr( $template, 0, $-[0] ) ) ;
155 # compile the nested chunk and save its parts
157 push @parts, $self->_compile_chunk( $1, $2, $indent ) ;
159 # chop off the pre-chunk and chunk
161 substr( $template, 0, $+[0], '' ) ;
164 # compile trailing text for scalars and save all of its parts
166 push @parts, $self->_compile_scalars( $template ) ;
168 # generate the code for this chunk
170 # start it with a do{} block open
172 my $code = "do {\n$indent" ;
174 # generate a lookup in data for this chunk name (unless it is the top
175 # level). this descends down the data tree during rendering
177 $code .= <<CODE . $indent if $chunk_name ;
178 my \$data = \$data->{$chunk_name} ;
181 # now generate the code to output all the parts of this chunk. they
182 # are all concatentated by the . operator
184 $code .= join( "\n$indent.\n$indent", @parts ) ;
186 # now we close the do block
189 $code .= "\n$indent}" ;
194 sub _compile_scalars {
196 my( $self, $template ) = @_ ;
198 # if the template is empty return no parts
200 return unless length $template ;
204 while( $template =~ m{$self->{scalar_re}}g ) {
206 # keep the text before the scalar markup and the code to access the scalar
209 dump_text( substr( $template, 0, $-[0] ) ),
212 substr( $template, 0, $+[0], '' ) ;
215 # keep any trailing text part
217 push @parts, dump_text( $template ) ;
228 return unless length $text ;
230 local( $Data::Dumper::Useqq ) = 1 ;
232 my $dumped = Dumper $text ;
234 $dumped =~ s/^[^"]+// ;
235 $dumped =~ s/;\n$// ;
242 my( $self, $template_name, $data ) = @_ ;
244 # render with cached code if we precompiled this template
246 if ( my $compiled = $self->{compiled_cache}{$template_name} ) {
248 return $compiled->($data) ;
251 # TODO: look for template by name
253 my $template = eval{ $self->_get_template($1) } ;
255 print "GOT [$template]\n" ;
257 # force the template into a ref
259 my $tmpl_ref = ref $template eq 'SCALAR' ? $template : \$template ;
261 my $rendered = $self->_render_includes( $tmpl_ref ) ;
263 #print "INC EXP <$rendered>\n" ;
266 $self->_render_chunk( $rendered, $data ) ;
269 croak "Template::Simple $@" if $@ ;
274 sub _render_includes {
276 my( $self, $tmpl_ref ) = @_ ;
278 # make a copy of the initial template so we can render it.
280 my $rendered = ${$tmpl_ref} ;
282 # loop until we can render no more include markups
285 s{$self->{include_re}}
286 { ${ $self->_get_template($1) }
294 HASH => \&_render_hash,
295 ARRAY => \&_render_array,
296 CODE => \&_render_code,
297 # if no ref then data is a scalar so replace the template with just the data
298 '' => sub { \$_[2] },
304 my( $self, $tmpl_ref, $data ) = @_ ;
306 #print "T ref [$tmpl_ref] [$$tmpl_ref]\n" ;
307 #print "CHUNK ref [$tmpl_ref] TMPL\n<$$tmpl_ref>\n" ;
309 #print Dumper $data ;
311 return \'' unless defined $data ;
313 # now render this chunk based on the type of data
315 my $renderer = $renderers{reftype $data || ''} ;
317 #print "EXP $renderer\nREF ", reftype $data, "\n" ;
319 die "unknown template data type '$data'\n" unless defined $renderer ;
321 return $self->$renderer( $tmpl_ref, $data ) ;
326 my( $self, $tmpl_ref, $href ) = @_ ;
328 return $tmpl_ref unless keys %{$href} ;
330 # we need a local copy of the template to render
332 my $rendered = ${$tmpl_ref} ;
335 # recursively render all top level chunks in this chunk
337 $rendered =~ s{$self->{chunk_re}}
339 # print "CHUNK $1\nBODY\n----\n<$2>\n\n------\n" ;
340 print "CHUNK $1\nBODY\n----\n<$2>\n\n------\n" ;
341 print "pre CHUNK [$`]\n" ;
342 ${ $self->_render_chunk( \"$2", $href->{$1} ) }
347 #print "HREF: ", Dumper $href ;
349 $rendered =~ s{$self->{scalar_re}}
351 # print "SCALAR $1 VAL $href->{$1}\n" ;
352 defined $href->{$1} ? $href->{$1} : ''
355 #print "HASH REND3\n<$rendered>\n" ;
362 my( $self, $tmpl_ref, $aref ) = @_ ;
364 # render this $tmpl_ref for each element of the aref and join them
368 #print "AREF: ", Dumper $aref ;
370 $rendered .= ${$self->_render_chunk( $tmpl_ref, $_ )} for @{$aref} ;
377 my( $self, $tmpl_ref, $cref ) = @_ ;
379 my $rendered = $cref->( $tmpl_ref ) ;
381 die <<DIE if ref $rendered ne 'SCALAR' ;
382 data callback to code didn't return a scalar or scalar reference
390 my( $self, $tmpls ) = @_ ;
392 #print Dumper $tmpls ;
393 return unless defined $tmpls ;
395 ref $tmpls eq 'HASH' or croak "templates argument is not a hash ref" ;
397 # copy all the templates from the arg hash and force the values to be
400 @{ $self->{tmpl_cache}}{ keys %{$tmpls} } =
401 map ref $_ eq 'SCALAR' ? \"${$_}" : \"$_", values %{$tmpls} ;
403 #print Dumper $self->{tmpl_cache} ;
408 sub delete_templates {
410 my( $self, @names ) = @_ ;
412 @names = keys %{$self->{tmpl_cache}} unless @names ;
414 delete @{$self->{tmpl_cache}}{ @names } ;
416 delete @{$self->{template_paths}}{ @names } ;
423 my( $self, $tmpl_name ) = @_ ;
425 #print "INC $tmpl_name\n" ;
427 my $tmpls = $self->{tmpl_cache} ;
429 # get the template from the cache and send it back if it was found there
431 my $template = $tmpls->{ $tmpl_name } ;
432 return $template if $template ;
434 # not found, so find, slurp in and cache the template
436 $template = $self->_find_template( $tmpl_name ) ;
437 $tmpls->{ $tmpl_name } = $template ;
444 my( $self, $tmpl_name ) = @_ ;
446 foreach my $dir ( @{$self->{include_paths}} ) {
448 my $tmpl_path = "$dir/$tmpl_name.tmpl" ;
450 #print "PATH: $tmpl_path\n" ;
451 next unless -r $tmpl_path ;
453 # cache the path to this template
455 $self->{template_paths}{$tmpl_name} = $tmpl_path ;
457 # slurp in the template file and return it as a scalar ref
459 return scalar read_file( $tmpl_path, scalar_ref => 1 ) ;
463 can't find template '$tmpl_name' in '@{$self->{include_paths}}'
468 1; # End of Template::Simple
474 Template::Simple - A simple and fast template module
482 use Template::Simple;
484 my $tmpl = Template::Simple->new();
486 my $template = <<TMPL ;
489 [%first%] - [%second%]
496 date => 'Jan 1, 2008',
497 author => 'Me, myself and I',
501 first => 'row 1 value 1',
502 second => 'row 1 value 2',
505 first => 'row 2 value 1',
506 second => 'row 2 value 2',
510 modified => 'Aug 31, 2006',
514 my $rendered = $tmpl->render( $template, $data ) ;
518 Template::Simple has these goals:
522 =item * Support most common template operations
524 It can recursively include other templates, replace tokens (scalars),
525 recursively render nested chunks of text and render lists. By using
526 simple idioms you can get conditional renderings.
528 =item * Complete isolation of template from program code
530 This is very important as template design can be done by different
531 people than the program logic. It is rare that one person is well
532 skilled in both template design and also programming.
534 =item * Very simple template markup (only 4 markups)
536 The only markups are C<INCLUDE>, C<START>, C<END> and C<token>. See
539 =item * Easy to follow rendering rules
541 Rendering of templates and chunks is driven from a data tree. The type
542 of the data element used in an rendering controls how the rendering
543 happens. The data element can be a scalar or scalar reference or an
544 array, hash or code reference.
546 =item * Efficient template rendering
548 Rendering is very simple and uses Perl's regular expressions
549 efficiently. Because the markup is so simple less processing is needed
550 than many other templaters. Precompiling templates is not supported
551 yet but that optimization is on the TODO list.
553 =item * Easy user extensions
555 User code can be called during an rendering so you can do custom
556 renderings and plugins. Closures can be used so the code can have its
557 own private data for use in rendering its template chunk.
563 You create a Template::Simple by calling the class method new:
565 my $tmpl = Template::Simple->new() ;
567 All the arguments to C<new()> are key/value options that change how
568 the object will do renderings.
574 This option sets the string or regex that is the starting delimiter
575 for all markups. You can use a plain string or a qr// but you need to
576 escape (with \Q or \) any regex metachars if you want them to be plain
577 chars. The default is qr/\[%/.
579 my $tmpl = Template::Simple->new(
583 my $rendered = $tmpl->render( '<%FOO%]', 'bar' ) ;
587 This option sets the string or regex that is the ending delimiter
588 for all markups. You can use a plain string or a qr// but you need to
589 escape (with \Q or \) any regex metachars if you want them to be plain
590 chars. The default is qr/%]/.
592 my $tmpl = Template::Simple->new(
596 my $rendered = $tmpl->render( '[%FOO%>', 'bar' ) ;
600 This boolean option will cause the regex that grabs a chunk of text
601 between the C<START/END> markups to become greedy (.+). The default is
602 a not-greedy grab of the chunk text. (UNTESTED)
606 This option lets you load templates directly into the cache of the
607 Template::Simple object. This cache will be searched by the C<INCLUDE>
608 markup which will be replaced by the template if found. The option
609 value is a hash reference which has template names (the name in the
610 C<INCLUDE> markup) for keys and their template text as their
611 values. You can delete or clear templates from the object cache with
612 the C<delete_template> method.
615 my $tmpl = Template::Simple->new(
619 [%baz%] is a [%quux%]
622 [%user%] is not a [%fool%]
627 my $template = <<TMPL ;
631 my $rendered = $tmpl->render(
641 Template::Simple can also load C<INCLUDE> templates from files. This
642 option lets you set the directory paths to search for those
643 files. Note that the template name in the C<INCLUDE> markup has the
644 .tmpl suffix appended to it when searched for in one of these
645 paths. The loaded file is cached inside the Template::Simple object
646 along with any loaded by the C<templates> option.
654 This method is passed a template and a data tree and it renders it and
655 returns a reference to the resulting string. The template argument can
656 be a scalar or a scalar reference. The data tree argument can be any
657 value allowed by Template::Simple when rendering a template. It can
658 also be a blessed reference (Perl object) since
659 C<Scalar::Util::reftype> is used instead of C<ref> to determine the
662 Note that the author recommends against passing in an object as this
663 breaks encapsulation and forces your object to be (most likely) a
664 hash. It would be better to create a simple method that copies the
665 object contents to a hash reference and pass that. But current
666 templaters allow passing in objects so that is supported here as well.
668 my $rendered = $tmpl->render( $template, $data ) ;
672 This method adds templates to the object cache. It takes a list of template names and texts just like the C<templates> constructor option.
674 $tmpl->add_templates(
676 foo => \$foo_template,
677 bar => '[%include bar%]',
681 =head2 delete_templates
683 This method takes a list of template names and will delete them from
684 the template cache in the object. If you pass in an empty list then
685 all the templates will be deleted. This can be used when you know a
686 template file has been updated and you want to get it loaded back into
687 the cache. Note that you can delete templates that were loaded
688 directly (via the C<templates> constructor option or the
689 C<add_templates> method) or loaded from a file.
691 # this deletes only the foo and bar templates from the object cache
693 $tmpl->delete_templates( qw( foo bar ) ;
695 # this deletes all of templates from the object cache
697 $tmpl->delete_templates() ;
699 =head2 get_dependencies
701 This method render the only C<INCLUDE> markups of a template and it
702 returns a list of the file paths that were found and loaded. It is
703 meant to be used to build up a dependency list of included templates
704 for a main template. Typically this can be called from a script (see
705 TODO) that will do this for a set of main templates and will generate
706 Makefile dependencies for them. Then you can regenerate rendered
707 templates only when any of their included templates have changed. It
708 takes a single argument of a template.
710 UNKNOWN: will this require a clearing of the cache or will it do the
711 right thing on its own? or will it use the file path cache?
714 $tmpl->get_dependencies( '[%INCLUDE top_level%]' );
718 All the markups in Template::Simple use the same delimiters which are
719 C<[%> and C<%]>. You can change the delimiters with the C<pre_delim>
720 and C<post_delim> options in the C<new()> constructor.
724 A token is a single markup with a C<\w+> Perl word inside. The token
725 can have optional whitespace before and after it. A token is replaced
726 by a value looked up in a hash with the token as the key. The hash
727 lookup keeps the same case as parsed from the token markup.
731 Those will be replaced by C<$href->{foo}> and C<$href->{BAR}> assuming
732 C<$href> is the current data for this rendering. Tokens are only
733 parsed out during hash data rendering so see Hash Data for more.
737 Chunks are regions of text in a template that are marked off with a
738 start and end markers with the same name. A chunk start marker is
739 C<[%START name%]> and the end marker for that chunk is C<[%END
740 name%]>. C<name> is a C<\w+> Perl word which is the name of this
741 chunk. The whitespace between C<START/END> and C<name> is required and
742 there is optional whitespace before C<START/END> and after the
743 C<name>. C<START/END> are case insensitive but the C<name>'s case is
744 kept. C<name> must match in the C<START/END> pair and it used as a key
745 in a hash data rendering. Chunks are the primary way to markup
746 templates for structures (sets of tokens), nesting (hashes of hashes),
747 repeats (array references) and callbacks to user code. Chunks are only
748 parsed out during hash data rendering so see Hash Data for more.
750 The body of text between the C<START/END> markups is grabbed with a
751 C<.+?> regular expression with the /s option enabled so it will match
752 all characters. By default it will be a non-greedy grab but you can
753 change that in the constructor by enabling the C<greedy_chunk> option.
763 =head1 RENDERING RULES
765 Template::Simple has a short list of rendering rules and they are easy
766 to understand. There are two types of renderings, include rendering
767 and chunk rendering. In the C<render> method, the template is an
768 unnamed top level chunk of text and it first gets its C<INCLUDE>
769 markups rendered. The text then undergoes a chunk rendering and a
770 scalar reference to that rendered template is returned to the caller.
772 =head2 Include Rendering
774 Include rendering is performed one time on a top level template. When
775 it is done the template is ready for chunk rendering. Any markup of
776 the form C<[%INCLUDE name]%> will be replaced by the text found in the
777 template C<name>. The template name is looked up in the object's
778 template cache and if it is found there its text is used as the
781 If a template is not found in the cache, it will be searched for in
782 the list of directories in the C<include_paths> option. The file name
783 will be a directory in that list appended with the template name and
784 the C<.tmpl> suffix. The first template file found will be read in and
785 stored in the cache. Its path is also saved and those will be returned
786 in the C<get_dependencies> method. See the C<add_templates> and
787 C<delete_templates> methods and the C<include_paths> option.
789 Rendered include text can contain more C<INCLUDE> markups and they
790 will also be rendered. The include rendering phase ends where there
791 are no more C<INCLUDE> found.
793 =head2 Chunk Rendering
795 A chunk is the text found between C<START> and C<END> markups and it
796 gets its named from the C<START> markup. The top level template is
797 considered an unamed chunk and also gets chunk rendered.
799 The data for a chunk determines how it will be rendered. The data can
800 be a scalar or scalar reference or an array, hash or code
801 reference. Since chunks can contain nested chunks, rendering will
802 recurse down the data tree as it renders the chunks. Each of these
803 renderings are explained below. Also see the IDIOMS and BEST PRACTICES
804 section for examples and used of these renderings.
806 =head2 Scalar Data Rendering
808 If the current data for a chunk is a scalar or scalar reference, the
809 chunk's text in the templated is replaced by the scalar's value. This
810 can be used to overwrite one default section of text with from the
813 =head2 Code Data Rendering
815 If the current data for a chunk is a code reference (also called
816 anonymous sub) then the code reference is called and it is passed a
817 scalar reference to the that chunk's text. The code must return a
818 scalar or a scalar reference and its value replaces the chunk's text
819 in the template. If the code returns any other type of data it is a
820 fatal error. Code rendering is how you can do custom renderings and
821 plugins. A key idiom is to use closures as the data in code renderings
822 and keep the required outside data in the closure.
824 =head2 Array Data Rendering
826 If the current data for a chunk is an array reference do a full chunk
827 rendering for each value in the array. It will replace the original
828 chunk text with the joined list of rendered chunks. This is how you do
829 repeated sections in Template::Simple and why there is no need for any
830 loop markups. Note that this means that rendering a chunk with $data
831 and [ $data ] will do the exact same thing. A value of an empty array
832 C<[]> will cause the chunk to be replaced by the empty string.
834 =head2 Hash Data Rendering
836 If the current data for a chunk is a hash reference then two phases of
837 rendering happen, nested chunk rendering and token rendering. First
838 nested chunks are parsed of of this chunk along with their names. Each
839 parsed out chunk is rendered based on the value in the current hash
840 with the nested chunk's name as the key.
842 If a value is not found (undefined), then the nested chunk is replaced
843 by the empty string. Otherwise the nested chunk is rendered according
844 to the type of its data (see chunk rendering) and it is replaced by
847 Chunk name and token lookup in the hash data is case sensitive (see
848 the TODO for cased lookups).
850 Note that to keep a plain text chunk or to just have the all of its
851 markups (chunks and tokens) be deleted just pass in an empty hash
852 reference C<{}> as the data for the chunk. It will be rendered but all
853 markups will be replaced by the empty string.
855 =head2 Token Rendering
857 The second phase is token rendering. Markups of the form [%token%] are
858 replaced by the value of the hash element with the token as the
859 key. If a token's value is not defined it is replaced by the empty
860 string. This means if a token key is missing in the hash or its value
861 is undefined or its value is the empty string, the [%token%] markup
862 will be deleted in the rendering.
864 =head1 IDIOMS and BEST PRACTICES
866 With all template systems there are better ways to do things and
867 Template::Simple is no different. This section will show some ways to
868 handle typical template needs while using only the 4 markups in this
873 This conditional idiom can be when building a fresh data tree or
874 modifying an existing one.
876 $href->{$chunk_name} = $keep_chunk ? {} : '' ;
878 If you are building a fresh data tree you can use this idiom to do a
881 $href->{$chunk_name} = {} if $keep_chunk ;
883 To handle an if/else conditional use two chunks, with the else chunk's
884 name prefixed with NOT_ (or use any name munging you want). Then you
885 set the data for either the true chunk (just the plain name) or the
886 false trunk with the NOT_ name. You can use a different name for the
887 else chunk if you want but keeping the names of the if/else chunks
888 related is a good idea. Here are two ways to set the if/else data. The
889 first one uses the same data for both the if and else chunks and the
890 second one uses different data so the it uses the full if/else code
893 $href->{ ($boolean ? '' : 'NOT_') . $chunk_name} = $data
896 $href->{ $chunk_name} = $true_data ;
898 $href->{ "NOT_$chunk_name" } = $false_data ;
901 NOTE TO ALPHA USERS: i am also thinking that a non-existing key or
902 undefined hash value should leave the chunk as is. then you would need
903 to explicitly replace a chunk with the empty string if you wanted it
904 deleted. It does affect the list of styles idiom. Any thoughts on
905 this change of behavior? Since this hasn't been released it is the
908 =head2 Chunked Includes
910 One of the benefits of using include templates is the ability to share
911 and reuse existing work. But if an included template has a top level
912 named chunk, then that name would also be the same everywhere where
913 this template is included. If a template included another template in
914 multiple places, its data tree would use the same name for each and
915 not allow unique data to be rendered for each include. A better way is
916 to have the current template wrap an include markup in a named chunk
917 markup. Then the data tree could use unique names for each included
918 template. Here is how it would look:
920 [%START foo_prime%][%INCLUDE foo%][%START foo_prime%]
922 [%START foo_second%][%INCLUDE foo%][%START foo_second%]
924 See the TODO section for some ideas on how to make this even more high level.
926 =head2 Repeated Sections
928 If you looked at the markup of Template::Simple you have noticed that
929 there is no loop or repeat construct. That is because there is no need
930 for one. Any chunk can be rendered in a loop just by having its
931 rendering data be an anonymous array. The renderer will loop over each
932 element of the array and do a fresh rendering of the chunk with this
933 data. A join (on '') of the list of renderings replaces the original
934 chunk and you have a repeated chunk.
936 =head2 A List of Mixed Styles
938 One formating style is to have a list of sections each which can have
939 its own style or content. Template::Simple can do this very easily
940 with just a 2 level nested chunk and an array of data for
941 rendering. The outer chunk includes (or contains) each of the desired
942 styles in any order. It looks like this:
944 [%START para_styles%]
946 [%INCLUDE para_style_main%]
949 [%INCLUDE para_style_sub%]
951 [%START footer_style%]
952 [%INCLUDE para_style_footer%]
956 The other part to make this work is in the data tree. The data for
957 para_styles should be a list of hashes. Each hash contains the data
958 for one pargraph style which is keyed by the style's chunk name. Since
959 the other styles's chunk names are not hash they are deleted. Only the
960 style which has its name as a key in the hash is rendered. The data
961 tree would look something like this:
965 main_style => $main_data,
968 sub_style => $sub_data,
971 sub_style => $other_sub_data,
974 footer_style => $footer_data,
980 The test scripts use a common test driver module in t/common.pl. It is
981 passed a list of hashes, each of which has the data for one test. A
982 test can create a ne Template::Simple object or use the one from the
983 previous test. The template source, the data tree and the expected
984 results are also important keys. See the test scripts for examples of
985 how to write tests using this common driver.
991 This is the name of the test and is used by Test::More
995 This is a hash ref of the options passed to the Template::Simple
996 constructor. The object is not built if the C<keep_obj> key is set.
1000 If set, this will make this test keep the Template::Simple object from
1001 the previous test and not build a new one.
1005 This is the template to render for this test. If not set, the test
1006 driver will use the template from the previous test. This is useful to
1007 run a series of test variants with the same template.
1011 This is the data tree for the rendering of the template.
1015 This is the text that is expected after the rendering.
1019 If set, this test is skipped.
1025 Even though this template system is simple, that doesn't mean it can't
1026 be extended in many ways. Here are some features and designs that
1027 would be good extensions which add useful functionality without adding
1028 too much complexity.
1030 =head2 Compiled Templates
1032 A commonly performed optimization in template modules is to precompile
1033 (really preparse) templates into a internal form that will render
1034 faster. Precompiling is slower than rendering from the original
1035 template which means you won't want to do it for each rendering. This
1036 means it has a downside that you lose out when you want to render
1037 using templates which change often. Template::Simple makes it very
1038 easy to precompile as it already has the regexes to parse out the
1039 markup. So instead of calling subs to do actual rendering, a
1040 precompiler would call subs to generate a compiled rendering tree.
1041 The rendering tree can then be run or processes with rendering data
1042 passed to it. You can think of a precompiled template as having all
1043 the nested chunks be replaced by nested code that does the same
1044 rendering. It can still do the dynamic rendering of the data but it
1045 saves the time of parsing the template souice. There are three
1046 possible internal formats for the precompiled template:
1052 This precompiler will generate source code that can be stored and/or
1053 eval'ed. The eval'ed top level sub can then be called and passed the
1056 =item Closure call tree
1058 The internal format can be a nested set of closures. Each closure would contain
1059 private data such as fixed text parts of the original template, lists
1060 of other closures to run, etc. It is trivial to write a basic closure
1061 generator which will make build this tree a simple task.
1063 =item Code ref call tree
1065 This format is a Perl data tree where the nodes have a code reference
1066 and its args (which can be nested instances of the same
1067 nodes). Instead of executing this directly, you will need a small
1068 interpreter to execute all the code refs as it runs through the tree.
1070 This would make for a challenging project to any intermediate Perl
1071 hacker. It just involves knowing recursion, data trees and code refs.
1072 Contact me if you are interested in doing this.
1076 =head2 Cased Hash Lookups
1078 One possible option is to allow hash renderings to always use upper or
1079 lower cased keys in their lookups.
1081 =head2 Render tokens before includes and chunks
1083 Currently tokens are rendered after includes and chunks. If tokens
1084 were rendered in a pass before the others, the include and chunk names
1085 could be dynamically set. This would make it harder to precompile
1086 templates as too much would be dynamic, i.e. you won't know what the
1087 fixed text to parse out is since anything can be included at render
1088 time. But the extra flexibility of changing the include and chunk
1089 names would be interesting. It could be done easily and enabled by an
1094 There are two different potential areas in Template::Simple that could
1095 use plugins. The first is with the rendering of chunkas and
1096 dispatching based on the data type. This dispatch table can easily be
1097 replaced by loaded modules which offer a different way to
1098 render. These include the precompiled renderers mentioned above. The
1099 other area is with code references as the data type. By defining a
1100 closure (or a closure making) API you can create different code refs
1101 for the rendering data. The range of plugins is endless some of the
1102 major template modules have noticed. One idea is to make a closure
1103 which contains a different Template::Simple object than the current
1104 one. This will allow rendering of a nested chunk with different rules
1105 than the current chunk being rendered.
1107 =head2 Data Escaping
1109 Some templaters have options to properly escape data for some types of
1110 text files such as html. this can be done with some variant of the
1111 _render_hash routine which also does the scalar rendering (which is
1112 where data is rendered). The rendering scalars code could be factored
1113 out into a set of subs one of which is used based on any escaping
1116 =head2 Data Tree is an Object
1118 This is a concept I don't like but it was requested so it goes into
1119 the TODO file. Currently C<render> can only be passed a regular
1120 (unblessed) ref (or a scalar) for its data tree. Passing in an object
1121 would break encapsulation and force the object layout to be a hash
1122 tree that matches the layout of the template. I doubt that most
1123 objects will want to be organized to match a template. I have two
1124 ideas, one is that you add a method to that object that builds up a
1125 proper (unblessed) data tree to pass to C<render>. The other is by
1126 subclassing C<Template::Simple> and overriding C<render> with a sub
1127 that does take an object hash and it can unbless it or build a proper
1128 data tree and then call C<render> in SUPER::. A quick solution is to
1129 use C<reftype> (from Scalar::Utils) instead of C<ref> to allow object
1130 hashes to be passed in.
1132 =head2 Includes and Closure Synergy
1134 By pairing up an include template along with code that can generate
1135 the appropriate data tree for its rendering, you can create a higher
1136 level template framework (the synergy). Additional code can be
1137 associated with them that will handle input processing and
1138 verification for the templates (e.g. web forms) that need it. A key to
1139 this will be making all the closures for the data tree. This can be
1140 greatly simplified by using a closure maker sub that can create all
1141 the required closures.
1143 =head2 Metafields and UI Generation
1145 Taking the synergy up to a much higher level is the concept of meta
1146 knowledge of fields which can generate templates, output processing
1147 (data tree generation), input processing, DB backing and more. If you
1148 want to discuss such grandiose wacky application schemes in a long
1149 rambling mind bending conversation, please contact me.
1151 =head2 More Examples and Idioms
1153 As I convert several scripts over to this module (they all used the
1154 hack version), I will add them to an examples section or possibly put
1155 them in another (pod only) module. Similarly the Idioms section needs
1156 rendering and could be also put into a pod module. One goal requested
1157 by an early alpha tester is to keep the primary docs as simple as the
1158 markup itself. This means moving all the extra stuff (and plenty of
1159 that) into other pod modules. All the pod modules would be in the same
1160 cpan tarball so you get all the docs and examples when you install
1165 Uri Guttman, C<< <uri at sysarch.com> >>
1169 Please report any bugs or feature requests to
1170 C<bug-template-simple at rt.cpan.org>, or through the web interface at
1171 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Template-Simple>.
1172 I will be notified, and then you'll automatically be notified of progress on
1173 your bug as I make changes.
1177 You can find documentation for this module with the perldoc command.
1179 perldoc Template::Simple
1181 You can also look for information at:
1185 =item * RT: CPAN's request tracker
1187 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Template-Simple>
1191 L<http://search.cpan.org/dist/Template-Simple>
1195 =head1 ACKNOWLEDGEMENTS
1197 I wish to thank Turbo10 for their support in developing this module.
1199 =head1 COPYRIGHT & LICENSE
1201 Copyright 2006 Uri Guttman, all rights reserved.
1203 This program is free software; you can redistribute it and/or modify it
1204 under the same terms as Perl itself.
1209 find templates and tests
1217 delete_templates test
1225 slurp dependency in makefile.pl