1package Template::Magic ; 2$VERSION = 1.39 ; 3use strict ; 4use 5.006_001 ; 5 6# This file uses the "Perlish" coding style 7# please read http://perl.4pro.net/perlish_coding_style.html 8 9; use Carp 10; $Carp::Internal{+__PACKAGE__}++ 11; use warnings::register 12; use Template::Magic::Zone 13; use IO::Util 14; use Class::Util 15; use File::Spec 16 17; sub NEXT_HANDLER () { 0 } 18; sub LAST_HANDLER () { 1 } 19 20; sub import 21 { my ($pkg, $pragma) = @_ 22 ; if ( $pragma 23 && $pragma eq '-compile' 24 ) 25 { carp "The -compile pragma has no effect since version 1.39" 26 if warnings::enabled 27 } 28 else 29 { require Exporter 30 ; our @ISA = 'Exporter' 31 ; our @EXPORT_OK = qw| NEXT_HANDLER 32 LAST_HANDLER 33 | 34 ; $pkg->export_to_level(1, @_) 35 } 36 } 37 38; sub new 39 { my ($c) = shift 40 ; my ($s) = @_ 41 ; $s = { @_ } # passing hash backward compatibility 42 unless ref $s eq 'HASH' 43 ; foreach ( keys %$s ) # passing -flag backward compatibility 44 { $$s{$_} = delete $$s{-$_} 45 if s/^-// 46 } 47 ; foreach ( values %$s ) # each value should be an ARRAY ref 48 { $_ = [ $_ ] 49 unless ref eq 'ARRAY' 50 } 51 ; bless $s, $c 52 ; $$s{markers} ||= $s->DEFAULT_MARKERS 53 ; $$s{output_handlers} ||= $s->DEFAULT_PRINT_HANDLERS 54 ; $$s{text_handlers} ||= $s->DEFAULT_TEXT_HANDLERS 55 || $$s{output_handlers} 56 ; $$s{zone_handlers} ||= $s->DEFAULT_ZONE_HANDLERS 57 ; $$s{value_handlers} ||= $s->DEFAULT_VALUE_HANDLERS 58 ; $$s{post_handlers} ||= $s->DEFAULT_POST_HANDLERS 59 ; $$s{lookups} ||= [ (caller)[0] ] 60 ; $$s{options} ||= $s->DEFAULT_OPTIONS 61 ; $$s{options} = { map { /^(no_)*(.+)$/ 62 ; $2 => $1 ? 0 : 1 63 } 64 @{$$s{options}} 65 } 66 ; foreach my $n qw| zone 67 value 68 text 69 output 70 post 71 | 72 { $$s{$n.'_handlers'} 73 &&= [ $s->_Hload( $$s{$n.'_handlers'} 74 , $n 75 ) 76 ] 77 } 78 ; $s 79 } 80 81; sub _Hload 82 { my ($s, $arr, $n) = @_ 83 ; map 84 { if ( ref eq 'CODE' ) 85 { $_ 86 } 87 elsif ( not ref ) 88 { my $C = $s->can($_) 89 || $s->can( join ( '_' 90 , $_ 91 , uc $n 92 , 'HANDLERS' 93 ) 94 ) 95 || croak qq(Unknown handler "$_") 96 ; my $ref = $s->$C 97 ; if ( ref $ref eq 'ARRAY' ) 98 { $s->_Hload( $ref, $n ) 99 } 100 elsif ( ref $ref eq 'CODE' ) 101 { $ref 102 } 103 } 104 } 105 @$arr 106 } 107 108; sub _re 109 { my ($s) = @_ 110 ; unless ( $$s{_re} ) # execute it just the first time AND if it has to parse 111 { unless ( @{$$s{markers}} == 3 ) 112 { no strict 'refs' 113 ; my $m = $$s{markers}[0] 114 ; my $M = $s->can($m) 115 || $s->can($m.'_MARKERS') # backward compatibility 116 || croak qq(Unknown markers "$m") 117 ; $$s{markers} = $s->$M 118 } 119 ; $$s{markers} = [ map { qr/$_/s 120 } 121 ( @{$$s{markers}} 122 , '(?:(?!' .$$s{markers}[2]. ').)*' 123 , '\w+' 124 ) 125 ] 126 ; my ($S, $I, $E, $A, $ID) = @{$$s{markers}} 127 ; $$s{_re}{label} = qr/$S$I*$ID$A$E/s 128 ; $$s{_re}{start_label} = qr/$S($ID)($A)$E/s 129 ; $$s{_re}{end_label} = qr/$S$I($ID)$E/s 130 ; $$s{_re}{include_label} = qr/$S\bINCLUDE_TEMPLATE\b($A)$E/s 131 } 132 133 ; wantarray 134 ? @{$$s{markers}} 135 : $$s{_re} 136 } 137 138; sub find_file 139 { my ($s, $t) = @_ 140 ; my $find = sub{(grep -s, @_)[0]} 141 ; File::Spec->file_name_is_absolute($t) 142 ? $find->($t) 143 : ( $ENV{TEMPLATE_MAGIC_ROOT} 144 && $find->( File::Spec->catfile( $ENV{TEMPLATE_MAGIC_ROOT} 145 , $t 146 ) 147 ) 148 || $find->( map File::Spec->catfile( $_ 149 , $t 150 ) 151 , @{$$s{paths}} 152 ) 153 || $ENV{TEMPLATE_MAGIC_ROOT} 154 && $find->( map File::Spec->catfile( $ENV{TEMPLATE_MAGIC_ROOT} 155 , $_ 156 , $t 157 ) 158 , @{$$s{paths}} 159 ) 160 || $find->($t) 161 ) 162 } 163 164; sub output 165 { my $s = shift 166 ; my $args 167 ; $$args{template} = shift 168 ; $$args{lookups} = [ @_ ] if @_ 169 ; IO::Util::capture { $s->_process( $args ) } 170 } 171 172; sub print 173 { my $s = shift 174 ; my $args 175 ; $$args{template} = shift 176 ; $$args{lookups} = [ @_ ] if @_ 177 ; $s->_process( $args ) 178 } 179 180; sub noutput 181 { my ($s, %args) = @_ 182 ; $args{lookups} = [ $args{lookups} ] 183 unless ref $args{lookups} eq 'ARRAY' 184 ; IO::Util::capture { $s->_process( \%args ) } 185 } 186 187; sub nprint 188 { my ($s, %args) = @_ 189 ; $args{lookups} = [ $args{lookups} ] 190 unless ref $args{lookups} eq 'ARRAY' 191 ; $s->_process( \%args ) 192 } 193 194; sub _process 195 { my ($s, $args) = @_ 196 ; $$s{_temp_lookups} = $$args{lookups} if exists $$args{lookups} 197 ; my $t 198 ; if ( $t = $$args{container_template} 199 || ${$$s{container_template}}[0] 200 ) 201 { $$s{_included_template} = $$args{template} 202 } 203 else 204 { $t = $$args{template} 205 } 206 ; my $z = $s->load( $t ) 207 ; $$z{tm} = $s 208 ; $z->content_process 209 ; delete $$z{tm} # to avoid tm object caching 210 ; delete @$s{qw|_included_template _temp_lookups _NOT_lookup|} 211 } 212 213; sub load 214 { my ($s, $t) = @_ 215 ; my $main_zone 216 ; if ( not ref $t ) 217 { $t = $s->find_file($t) 218 or croak qq(Template file "$t" empty or not found) 219 ; if ( $$s{options}{cache} ) 220 { $main_zone = IO::Util::_get_parsing_cache('magic_zone', $t) 221 ; return $main_zone if $main_zone 222 } 223 } 224 ; my $content = ref $t eq 'SCALAR' ? $t : IO::Util::slurp $t 225 ; $main_zone = $s->_parse( $content ) 226 ; $$s{options}{cache} &&! ref($t) # set cache 227 && IO::Util::_set_parsing_cache 'magic_zone', $t, $main_zone 228 ; $main_zone 229 } 230 231; sub purge_cache 232 { $_[0] = 'magic_zone' 233 ; goto &IO::Util::_purge_parsing_cache 234 } 235 236; sub _parse 237 { my ($s, $content_ref) = @_ 238 ; my $re = $s->_re 239 ; my @temp 240 = map { [ $_ 241 , do { /$$re{end_label}/ && $1 242 || /$$re{include_label}/ && do{ (my $t = $1) =~ s/^\s+// 243 ; $t 244 ? $s->load($t) 245 : 'CONTAINER_INCLUDE' 246 } 247 || /$$re{start_label}/ && { id => $1 248 , attributes => $2 249 } 250 } 251 ] 252 } 253 split /($$re{label})/ , $$content_ref 254 ; for ( my $i = $#temp # find end 255 ; $i >= 0 256 ; $i -- 257 ) 258 { my $id = $temp[$i][1] 259 ; next if ( ref $id or not $id ) 260 ; for ( ( my $ii = $i-1 # find THE start 261 , my $l = 0 262 ) 263 ; $ii >= 0 # condition 264 ; ( $ii -- 265 , $l ++ 266 ) 267 ) 268 { my $the_start = $temp[$ii][1] 269 ; next unless ref($the_start) eq 'HASH' # next if not start 270 ; next unless $$the_start{id} eq $id # next if not THE start 271 ; $$the_start{_s} = $ii + 1 272 ; $$the_start{_e} = $ii + $l 273 ; last 274 } 275 } 276 # allows to set protected props from outside class 277 ; local $Class::props::force = 1 278 ; Template::Magic::Zone->new( _s => 0 279 , _e => $#temp 280 , _t => \@temp 281 , is_main => 1 282 ) 283 } 284 285 286############################# STANDARD HANDLERS ############################# 287 288# override these DEFAULT subs in subclasses to change defaults 289 290; sub DEFAULT_ZONE_HANDLERS 291 { 292 } 293 294; sub DEFAULT_POST_HANDLERS 295 { 296 } 297 298; sub DEFAULT_TEXT_HANDLERS 299 { 300 } 301 302; sub DEFAULT_VALUE_HANDLERS 303 { my ($s, @args) = @_ 304 ; [ $s->SCALAR 305 , $s->REF 306 , $s->CODE(@args) 307 , $s->ARRAY 308 , $s->HASH 309 , $s->OBJECT 310 ] 311 } 312 313; sub DEFAULT_PRINT_HANDLERS 314 { [ sub 315 { print $_[1] if defined $_[1] 316 ; NEXT_HANDLER 317 } 318 ] 319 } 320 321; { no warnings 'once' 322 ; *DEFAULT_OUTPUT_HANDLERS = \&DEFAULT_PRINT_HANDLER # deprecated 323 } 324 325; sub DEFAULT_OPTIONS 326 { [ qw| cache | ] 327 } 328 329; sub DEFAULT_MARKERS 330 { [ qw| { / } | ] 331 } 332 333; sub HTML_MARKERS 334 { [ qw| <!--{ / }--> | ] 335 } 336 337; sub CODE_MARKERS 338 { [ qw| <- / -> | ] 339 } 340 341; sub HTML_VALUE_HANDLERS # value handler 342 { my ($s, @args) = @_ 343 ; [ $s->SCALAR 344 , $s->REF 345 , $s->CODE(@args) 346 , $s->TableTiler 347 , $s->ARRAY 348 , $s->HASH 349 , $s->FillInForm 350 , $s->OBJECT 351 ] 352 } 353 354; sub SCALAR # value handler 355 { sub 356 { my ($z) = @_ 357 ; my $v = $z->value 358 ; if ( not ref $v ) # if it's a plain string 359 { $z->output($v) # set output 360 ; $z->output_process( $v ) # process output (requires string) 361 ; LAST_HANDLER 362 } 363 } 364 } 365 366; sub REF # value handler 367 { sub 368 { my ($z) = @_ 369 ; my $v = $z->value 370 ; if (ref($v) =~ /^(SCALAR|REF)$/) # if it's a reference 371 { $z->value($$v) # dereference 372 ; $z->value_process # process the new value 373 ; LAST_HANDLER 374 } 375 } 376 } 377 378; sub ARRAY # value handler 379 { sub 380 { my ($z) = @_ 381 ; if (ref $z->value eq 'ARRAY') # if it's an ARRAY 382 { my ($i, $attr, $val_key, $ix_key, $named) = 0 383 ; if ( $attr = $z->attributes ) 384 { $attr =~ s/^\s*(OF\s)*\s*//i 385 ; ($val_key, $ix_key, $i) = split /\s+/, $attr 386 ; $named = 1 387 } 388 ; foreach my $item ( @{$z->value} ) # for each value in the array 389 { $z->value( $named # set the value for the zone 390 ? { $val_key => $item 391 , $ix_key ? ($ix_key => $i ++) : () 392 } 393 : $item 394 ) 395 ; $z->value_process # process it 396 } 397 ; LAST_HANDLER 398 } 399 } 400 } 401 402; sub HASH # value handler 403 { sub 404 { my ($z) = @_ 405 ; if (ref $z->value eq 'HASH') # if it's a HASH 406 { $z->content_process # start again the process 407 ; LAST_HANDLER 408 } 409 } 410 } 411 412; sub CODE # value handler 413 { my ( undef, @args ) = @_ 414 ; sub 415 { my ($z) = @_ 416 ; my $v = $z->value 417 ; if ( ref $v eq 'CODE' ) 418 { my $l = $z->location 419 ; my $nv = Class::Util::blessed($l) 420 ? do { no strict 'refs' 421 ; $l->$v( ${ref($l).'::no_template_magic_zone'} 422 ? () 423 : $z 424 , @args 425 ) 426 } 427 : $v->( $z , @args ) 428 ; if ( $v ne ($nv||'') ) # avoid infinite loop 429 { $z->value($nv) 430 ; $z->value_process 431 } 432 ; LAST_HANDLER 433 } 434 } 435 } 436 437; sub OBJECT 438 { sub 439 { my ($z) = @_ 440 ; if ( Class::Util::blessed($z->value) ) 441 { $z->content_process # process content 442 ; LAST_HANDLER 443 } 444 } 445 } 446 447; sub ID_list 448 { my ($s, $indent, $end) = @_ 449 ; $indent ||= ' ' x 4 450 ; $end ||= '/' 451 ; my $re = $s->_re 452 ; $$s{text_handlers} = [ sub{} ] # does not print any text 453 ; $$s{zone_handlers} 454 = [ sub # takes control of the whole process 455 { my ($z) = @_ 456 ; $z->output_process( $indent x $z->level 457 . $z->id 458 . ":\n" 459 ) 460 ; $z->content_process 461 ; my $cont = $z->content 462 ; if ( $z->_e # if it is a block 463 && $cont =~ /$$re{label}/ # and contains labels 464 ) 465 { $z->output_process( $indent x $z->level # print the end 466 . $end 467 . $z->id 468 . ":\n" 469 ) 470 } 471 ; LAST_HANDLER 472 } 473 ] 474 } 475 476# START AutoLoaded handlers 477 478# 'sub' must be at start of line to be found by AutoSplit 479# no fancy coding here :-( 480 481sub _EVAL_ # zone handler 482 { sub 483 { my ($z) = @_; 484 ; if ( $z->id eq '_EVAL_' ) 485 { $z->value( eval $z->content ) 486 } 487 ; NEXT_HANDLER 488 # lookup is skipped by the defined $z->value 489 # value_process is entered by default 490 } 491 } 492 493sub _EVAL_ATTRIBUTES_ # zone handler 494 { sub 495 { my ($z) = @_ 496 ; if ( $z->attributes ) 497 { $z->param( eval $z->attributes ) 498 } 499 ; NEXT_HANDLER 500 # $z->attributes should be a ref to a structure 501 } 502 } 503 504sub TRACE_DELETIONS # zone handler 505 { sub 506 { my ($z) = @_ 507 # do lookup and value processes as usual 508 ; $z->lookup_process 509 ; $z->value_process 510 # if they fail to find a true output trace the deletion 511 ; if ( not defined $z->output ) 512 { $z->output_process ( '<<' . $z->id . ' not found>>' ) 513 unless ref $z->value eq 'HASH' 514 } 515 elsif ( not $z->output ) 516 { $z->output_process ( '<<' . $z->id . ' found but empty>>' ) 517 } 518 ; LAST_HANDLER 519 } 520 } 521 522sub INCLUDE_TEXT # zone handler 523 { sub 524 { my ($z) = @_ 525 ; if ( $z->id eq 'INCLUDE_TEXT' ) 526 { my $file = $z->attributes 527 ; open my $itxt, $file 528 or croak qq(Error opening text file "$file": $^E) 529 ; $z->text_process($_) while <$itxt> 530 ; close $itxt 531 ; LAST_HANDLER 532 } 533 } 534 } 535 536############### HTML HANDLERS ############## 537 538sub TableTiler # value handler 539 { eval 540 { local $SIG{__DIE__} 541 ; require HTML::TableTiler 542 ; return $HTML::TableTiler::VERSION >= 1.14 543 } 544 ; if ( $@ ) 545 { carp qq("HTML::TableTiler" is not installed on this system or it is not current\n) 546 ; return sub {} # no action 547 } 548 else 549 { sub # normal handler 550 { my ($z) = @_ 551 ; my $v = $z->value 552 ; if ( ref($v) eq 'ARRAY' 553 && HTML::TableTiler::is_matrix($v) # if matrix 554 ) 555 { $z->value 556 ( do { my $cont = $z->content 557 ; HTML::TableTiler::tile_table( $v 558 , $cont && \$cont 559 , $z->attributes 560 , 1 561 ) 562 } 563 ) 564 ; $z->value_process 565 ; LAST_HANDLER 566 } 567 } 568 } 569 } 570 571sub FillInForm # value handler 572 { eval 573 { local $SIG{__DIE__} 574 ; require HTML::FillInForm 575 } 576 ; if ( $@ ) 577 { carp qq("HTML::FillInForm" is not installed on this system\n) 578 ; sub {} 579 } 580 else 581 { sub 582 { my ($z) = @_ 583 ; my $v = $z->value 584 ; if ( ref($v) 585 && defined UNIVERSAL::can( $v , 'param' ) 586 ) 587 { my $cont = IO::Util::capture { $z->content_process } 588 ; my $attr = $z->attributes 589 ; my ($list) = $attr =~ /ignore_fields\s*=>\s*\[(.*)\]/ 590 ; my @if = map /(?:'|")(.+)(?:'|")/ #' 591 , split /\s*,\s*/ 592 , $list||'' 593 ; $z->value( HTML::FillInForm 594 ->new 595 ->fill( scalarref => $cont 596 , fobject => $v 597 , ignore_fields => \@if 598 ) 599 ) 600 ; $z->value_process 601 ; LAST_HANDLER 602 } 603 } 604 } 605 } 606 607__END__ 608 609=pod 610 611=head1 NAME 612 613Template::Magic - Magic merger of runtime values with templates 614 615=head1 VERSION 1.39 616 617Included in Template-Magic 1.39 distribution. 618 619The latest version changes are reported in the F<Changes> file in this distribution. 620 621=head1 INSTALLATION 622 623=over 624 625=item Prerequisites 626 627 Perl version >= 5.6.1 628 OOTools >= 2 629 IO::Util >= 1.46 630 File::Spec >= 0 631 632=item CPAN 633 634If you want to install Template::Magic plus all related extensions (the prerequisites to use also L<Template::Magic::HTML|Template::Magic::HTML>), all in one easy step: 635 636 perl -MCPAN -e 'install Bundle::Template::Magic' 637 638=item Standard installation 639 640From the directory where this file is located, type: 641 642 perl Makefile.PL 643 make 644 make test 645 make install 646 647B<Note>: this installs just the main distribution and does not install the prerequisites of L<Template::Magic::HTML|Template::Magic::HTML>. 648 649=item Distribution structure 650 651 Bundle::Template::Magic a bundle to install everything in one step 652 Template::Magic the main module 653 Template::Magic::Zone defines the zone object 654 Template::Magic::HTML handlers useful in HTML environment 655 656=back 657 658=head1 SYNOPSIS 659 660Just add these 2 magic lines to your code... 661 662 use Template::Magic; 663 Template::Magic->new->print( '/path/to/template' ); 664 665to have all your variable and subroutines merged with the F<template> file, or set one or more constructor array to customize the output generation as you need: 666 667 use Template::Magic qw( -compile ); 668 669 $tm = new Template::Magic 670 paths => [ qw(/any/path /any/other/path) ] , 671 markers => [ qw( < / > ) ] , 672 lookups => [ \%my_hash, $my_obj, 'main' ] , 673 zone_handlers => [ \&my_zone_handler, '_EVAL_' ] , 674 value_handlers => [ 'DEFAULT', \&my_value_handler ] , 675 text_handlers => sub {print lc $_[1]} , 676 output_handlers => sub {print uc $_[1]} , 677 post_handlers => \&my_post_handler , 678 options => 'no_cache' ; 679 680 $tm->nprint( template => '/path/to/template' 681 lookups => \%my_special_hash ); 682 683=head1 DESCRIPTION 684 685Template::Magic is a "magic" interface between programming and design. It makes "magically" available all the runtime values - stored in your variables or returned by your subroutines - inside a static template file. B<In simple cases there is no need to assign values to the object>. Template outputs are linked to runtime values by their I<identifiers>, which are added to the template in the form of simple I<labels> or I<blocks> of content. 686 687 a label: {identifier} 688 a block: {identifier} content of the block {/identifier} 689 690From the designer point of view, this makes things very simple. The designer has just to decide B<what> value and B<where> to put it. Nothing else is required, no complicated new syntax to learn! B<This feature make this template system the perfect choice when the templates file has to be edited by unskilled people>. 691 692On the other side, the programmer has just to define variables and subroutines as usual and their values will appear in the right place within the output. The automatic interface allows the programmer to focus just on the code, saving him the hassle of interfacing code with output, and even complicated output - with complex switch branching and nested loops - can be easily organized by minding just a few simple concepts. 693 694=over 695 696=item 1 697 698The object parses the template and searches for any I<labeled zone> 699 700=item 2 701 702When a I<zone> is found, the object looks into your code and searches for any variable or sub with the same identifier (name) 703 704=item 3 705 706When a match is found the object replaces the label or the block with the value returned by the variable or sub found into your code (dereferencing and/or executing code as needed). (see L<"Understand the output generation"> for details) 707 708=back 709 710B<Note>: If you are planning to use this module in CGI environment, take a look at L<CGI::Builder::Magic|CGI::Builder::Magic> that transparently integrates this module in a very handy and powerful framework. 711 712=head2 Simple example 713 714The following is a very simple example only aimed to better understand how it works: obviously, the usefulness of Template::Magic comes up when the output become more complex. 715 716Imagine you need an output that looks like this template file: 717 718 City: {city} 719 Date and Time: {date_and_time} 720 721where {city} and {date_and_time} are just placeholder that you want to be replaced in the output by some real runtime values. Somewhere in your code you have defined a scalar and a sub to return the 'city' and the 'date_and_time' values: 722 723 $city = 'NEW YORK'; 724 sub date_and_time { localtime } 725 726you have just to add these 2 magic lines to the code: 727 728 use Template::Magic; 729 Template::Magic->new->print( 'my_template_file' ); 730 731to generate this output: 732 733 City: NEW YORK 734 Date and Time: Sat Nov 16 21:03:31 2002 735 736With the same 2 magic lines of code, Template::Magic can automatically look up values from I<scalars>, I<arrays>, I<hashes>, I<references> and I<objects> from your code and produce very complex outputs. The default settings are usually smart enough to do the right job for you, however if you need complete control over the output generation, you can fine tune them by controlling them explicitly. See L<"CUSTOMIZATION"> for details. 737 738=head2 More complex example 739 740=over 741 742=item the template 743 744The template file F<'my_template_file'>... I<(this example uses plain text for clarity, but Template::Magic works with any type of text file)> 745 746 A scalar variable: {a_scalar}. 747 A reference to a scalar variable: {a_ref_to_scalar}. 748 A subroutine: {a_sub} 749 A reference to subroutine: {a_ref_to_sub} 750 A reference to reference: {a_ref_to_ref} 751 A hash: {a_hash}this block contains a {a_scalar} and a {a_sub}{/a_hash} 752 753 A loop:{an_array_of_hashes} 754 Iteration #{ID}: {guy} is a {job}{/an_array_of_hashes} 755 756 An included file: 757 {INCLUDE_TEMPLATE my_included_file} 758 759... and another template file F<'my_included_file'> that will be included... 760 761 this is the included file 'my_included_file' 762 that contains a label: {a_scalar} 763 764=item the code 765 766... some variables and subroutines already defined somewhere in your code... 767 768B<Note>: This example uses globals just for simplicity. Please notice that Template::Magic can be used to write sloppy code or very strict code, exactly as perl itself can. Magic lookups is a very handly feature for simple scripts, while it is not recommended for complex script where you should explicitly limit the lookups to some specific package or hash (see L<"lookups">). 769 770 $a_scalar = 'THIS IS A SCALAR VALUE'; 771 $a_ref_to_scalar = \$a_scalar; 772 @an_array_of_hashes = ( { ID => 1, guy => 'JOHN SMITH', job => 'PROGRAMMER' }, 773 { ID => 2, guy => 'TED BLACK', job => 'WEBMASTER' }, 774 { ID => 3, guy => 'DAVID BYRNE', job => 'MUSICIAN' } ); 775 %a_hash = ( a_scalar => 'NEW SCALAR VALUE' 776 a_sub => sub { 'NEW SUB RESULT' } ); 777 778 sub a_sub { 'THIS SUB RETURNS A SCALAR' } 779 sub a_ref_to_sub { \&a_sub } 780 sub a_ref_to_ref { $a_ref_to_scalar } 781 782Just add these 2 magic lines... 783 784 use Template::Magic; 785 Template::Magic->new->print( 'my_template_file' ); 786 787=item the output 788 789I<(in this example Lower case are from templates and Upper case are from code)>: 790 791 A scalar variable: THIS IS A SCALAR VALUE. 792 A reference to a scalar variable: THIS IS A SCALAR VALUE. 793 A subroutine: THIS SUB RETURNS A SCALAR 794 A reference to subroutine: THIS SUB RETURNS A SCALAR 795 A reference to reference: THIS IS A SCALAR VALUE 796 A hash: this block contains a NEW SCALAR VALUE and a NEW SUB RESULT 797 798 A loop: 799 Iteration #1: JOHN SMITH is a PROGRAMMER 800 Iteration #2: TED BLACK is a WEBMASTER 801 Iteration #3: DAVID BYRNE is a MUSICIAN 802 803 An included file: 804 this is the included file 'my_included_file' 805 that contains a label: THIS IS A SCALAR VALUE. 806 807=back 808 809=head2 Features 810 811Since syntax and coding related to this module are very simple and mostly automatic, you should careful read this section to have the right idea about its features and power. This is a list - with no particular order - of the most useful features and advantages: 812 813=over 814 815=item * Simple, flexible and powerful to use 816 817In simple cases, you will have just to use L<new()|"new ( [constructor_arrays] )"> and L<print(template)|"print ( template [, temporary lookups ] )"> methods, without having to pass any other value to the object: it will do the right job for you. However you can fine tune the behaviour as you need. (see L<"CUSTOMIZATION">) 818 819=item * Extremely simple and configurable template syntax 820 821The template syntax is so simple and code-independent that even the less skilled webmaster will manage it without bothering you :-). By default Template::Magic recognizes labels in the form of simple identifiers surrounded by braces (I<{my_identifier}>), but you can easily use different markers (see L<"Redefine Markers">). 822 823=item * Automatic or manual lookup of values 824 825By default, Template::Magic compares any I<label identifier> defined in your template with any I<variable> or I<subroutine identifier> defined in the caller namespace. However, you can explicitly define the lookup otherwise, by passing a list of package namespaces, hash references and blessed objects to the C<lookups> constructor array. 826 827=item * Unlimited nested included templates 828 829Sometimes it can be useful to split a template into differents files. No nesting limit when including files into files. (see L<"Include and process a template file">) 830 831=item * Branching 832 833You can easily create simple or complex if-elsif-else conditions to print just the blocks linked with the true conditions (see L<"Setup an if-else condition"> and L<"Setup a switch condition">) 834 835=item * Unlimited nested loops 836 837When you need complex outputs you can build any immaginable nested loop, even mixed with control switches and included templates (see L<"Build a loop"> and L<"Build a nested loop">) 838 839=item * Scalable and expandable extensions system 840 841You can load only the handlers you need, to gain speed, or you can add as many handlers you will use, to gain features. You can even write your own extension handler in just 2 or 3 lines of code, expanding its capability for your own purpose. (see L<"CUSTOMIZATION"> ) 842 843=item * Efficient and fast 844 845The internal rapresentation and storage of templates allows minimum memory requirement and completely avoid wasting copies of content. You can even include external (and probably huge) text files in the output without memory charges. (see L<"Include (huge) text files without memory charges">) 846 847=item * Automatic caching of template files 848 849Under mod_perl it could be very useful to have the template structure cached in memory, already parsed and ready to be used (almost) without any other process. Template::Magic opens and parses a template file only the first time or if the file has been modified. 850 851=item * Perl embedding 852 853Even if I don't encourage this approach, however you can very easily embed any quantity of perl code into any template. (see L<"Embed perl into a template">) 854 855=item * Placeholders and simulated areas 856 857Placeholders and simulated areas can help in designing the template for a more consistent preview of the final output. (see L<"Setup placeholders"> and L<"Setup simulated areas">) 858 859=item * Labels and block list 860 861When you have to deal with a webmaster, you can easily print a pretty formatted output of all the identifiers present in a template. Just add your description of each label and block and save hours of explanations ;-) (see L<ID_list()|"ID_list ( [indentation_string [, end_marker]] )"> static method) 862 863=item * Simple to maintain 864 865Change your code and Template::Magic will change its behaviour accordingly. In most cases you will not have to reconfigure, either the object, or the template. 866 867=item * Simply portable 868 869This module and its extensions are written in pure perl. You don't need any compiler in order to install it on any platform so you can distribute it with your own applications by just including a copy of its files (in this case just remember to AutoSplit the modules or take off the '__END__'). 870 871=back 872 873=head2 Policy 874 875The main principle of Template::Magic is: B<keeping the designing separated from the coding>, giving all the power to the programmer and letting designer do only design. In other words: while the code includes ALL the active and dynamic directions to generate the output, the template is a mere passive and static file, containing just placeholder (zones) that the code will replace with real data. 876 877This philosophy keeps both jobs very tidy and simple to do, avoiding confusion and enforcing clearness, specially when programmer and designer are 2 different people. But another aspect of the philosophy of Template::Magic is flexibility, something that gives you the possibility to easily B<bypass the rules>. 878 879Even if I don't encourage breaking the main principle (keeping the designing separated from the coding), sometimes you might find useful to put inside a template some degree of perl code, or may be you want just to interact DIRECTLY with the content of the template. See L<"Use subroutines to rewrite links"> and L<"Embed perl into a template"> for details. 880 881Other important principles of Template::Magic are scalability and expandability. The whole extension system is built on these principles, giving you the possibility of control the behaviour of this module by omitting, changing the orders and/or adding your own handlers, without the need of subclassing the module. See L<"CUSTOMIZATION">. 882 883=head2 Useful links 884 885=over 886 887=item * 888 889A simple and useful navigation system between my modules is available at this URL: http://perl.4pro.net 890 891=item * 892 893More practical topics are discussed in the mailing list at this URL: http://lists.sourceforge.net/lists/listinfo/template-magic-users 894 895=back 896 897=head1 METHODS 898 899=head2 new ( [constructor_arrays] ) 900 901If you use just the defaults, you can construct the new object by writing this: 902 903 $tm = new Template::Magic ; 904 905If you don't pass any parameter to the constructor method, the constructor defaults are usually smart enough to do the right job for you, but if you need complete control over the output generation, you can fine tune it by controlling it explicitly. I<(see the section L<"Constructor Arrays">)>. 906 907=head2 output ( template [, temporary lookups ] ) 908 909B<WARNING>: this method is here for historical reasons, but it is not the maximum of efficiency. Please consider to use the L<print()|"print ( template [, temporary lookups ] )"> method when possible I<(see L<"EFFICIENCY">)>. You can also consider to write an I<output handler> that fits your needs but process the output content on the fly and without the need to collect the whole output as this method does. 910 911B<Note:> If you need to use C<Template::Magic> with C<CGI::Application> (that requires the run modes method to collect the whole output) you may use L<CGI::Application::Magic|CGI::Application::Magic> or L<Apache::Application::Magic|Apache::Application::Magic> that transparently integrates the template system with the application and avoid this method. 912 913This method merges the runtime values with the template and returns a reference to the whole collected output. It accepts one I<template> parameter that can be a reference to a SCALAR content, a path to a template file or a filehandle. 914 915This method accepts any number of I<temporary lookups> elements that could be I<package names>, I<blessed objects> and I<hash references> (see L<"lookups"> to a more detailed explanation). 916 917 # template is a path 918 $output = $tm->output( '/path/to/template' ) ; 919 920 # template is a reference (not efficient but possible) 921 $output = $tm->output( \$tpl_content ) ; 922 923 # template is a filehandler 924 $output = $tm->output( \*FILEHANDLER ) ; 925 926 # this adds some lookups location to the print method 927 $my_block_output = $tm->output( '/path/to/template', \%special_hash ); 928 929 930B<Note>: if I<template> is a path, the object will cache it automatically, so Template::Magic will open and parse the template file only the first time or if the file has been modified. If for any reason you don't want to cache the template structure, you can use the 'cache / no_cache' L<"options">. 931 932=head2 noutput ( arguments ) 933 934A named arguments interface for the L<output()|"output ( template [, temporary lookups ] )"> method, which add also the possibility to pass the 'container_template' argument. 935 936 $tm->nprint( template => '/path/to/template', 937 lookups => [ \%special_hash, 'My::lookups'], 938 container_template => '/path/to/container_template') ; 939 940=head2 print ( template [, temporary lookups ] ) 941 942This method merges the runtime values with the template and prints the output. It accepts one I<template> parameter that can be a reference to a SCALAR content, a path to a template file or a filehandle. 943 944This method accepts any number of I<temporary lookups> elements that could be I<package names>, I<blessed objects> and I<hash references> (see L<"lookups"> to a more detailed explanation). 945 946 # template is a path 947 $tm->print( '/path/to/template' ); 948 949 # template is a reference (not efficient but possible) 950 $tm->print( \$tpl_content ) ; 951 952 # template is a filehandler 953 $tm->print( \*FILEHANDLER ); 954 955 # this adds some lookups location to the print method 956 $tm->print( '/path/to/template', \%special_hash ); 957 958B<Note>: if I<template> is a path, the object will cache it automatically, so Template::Magic will open and parse the template file only the first time or if the file has been modified. If for any reason you don't want to cache the template structure, you can use the 'cache / no_cache' L<"options">. I<(see L<"EFFICIENCY">)>. 959 960=head2 nprint ( arguments ) 961 962A named arguments interface for the L<print()|"print ( template [, temporary lookups ] )"> method, which add also the possibility to pass the 'container_template' argument. 963 964 $tm->nprint( template => '/path/to/template', 965 lookups => [ \%special_hash, 'My::lookups'], 966 container_template => '/path/to/container_template') ; 967 968=head2 ID_list ( [indentation_string [, end_marker]] ) 969 970Calling this method (before the L<output()|"output ( template [, temporary lookups ] )"> or L<print()|"print ( template [, temporary lookups ] )"> methods) will redefine the behaviour of the module, so your program will print a pretty formatted list of only the identifiers present in the template, thus the programmer can pass a description of each label and block within a template to a designer. 971 972The method accepts an I<indentation string> (usually a tab character or a few spaces), that will be used to indent nested blocks. If you omit the indentation string 4 spaces will be used. The method accepts also as second parameter an I<end marker> string, which is used to distinguish the end label in a container block. If you omit this, a simple '/' will be used. 973 974 # defalut 975 $tm->ID_list; 976 977 # custom indentation 978 $tm->ID_list("\t", 'END OF '); 979 980See also L<"Prepare the identifiers description list">. 981 982=head2 load( template ) 983 984This method explicitly (pre)loads and parses the template in order to cache it for future use. 985You shouldn't need to use this method unless you want to build the cache in advance (e.g the F<startup.pl> for C<mod_perl> advanced users). 986 987=head2 purge_cache ( [template_path] ) 988 989Template::Magic opens and parses a template file only the first time or if the file has been modified. Since the template caching is automatic you shouldn't need to use this method under normal situations, anyway with this method you can purge the I<template_path> from the cache. Without any I<template_path> parameter the method purges all the stored templates. 990 991=head2 find_file ( template ) 992 993This method is internally used to find the templates you pass with C<print(), nprint(), output(), noutput()> methods or an 'INCLUDE_TEMPLATE' label (and its relative Zone method C<include_template>). 994 995You usually don't need to use this method explicitly, unless you want to check if a template exists on your own. If a non-zero size file exists it returns the path of the found template, or undef if it doesn't. 996 997The I<template> specified can be an absolute path (beginning with a '/' under 998Unix, for example). If it isn't absolute, the path in the environment variable 999TEMPLATE_MAGIC_ROOT is tried, if it exists. Next the paths in the B<paths> constructor array are tried, first as they are, and then with TEMPLATE_MAGIC_ROOT prepended if available. As a final attempt, the I<template> is checked directly. 1000 1001=head1 CUSTOMIZATION 1002 1003B<Note>: You can completely skip this section if you plan to use just the defaults. 1004 1005The output generation can be completely customized during the creation of the new object by passing to the C<new()> method one or more L<"Constructor Arrays">. 1006 1007=head2 Constructor Arrays 1008 1009The new() method accepts one optional hash that can contain the following optionals constructor arrays: 1010 1011 markers 1012 lookups 1013 zone_handlers 1014 value_handlers 1015 text_handlers 1016 output_handlers 1017 post_handlers 1018 paths 1019 options 1020 container_template 1021 1022Constructor Arrays are array references containing elements that can completely change the behaviour of the object and even add code not directly related with the output generation but executed during the process. 1023 1024All the constructor arrays should be array references, but if you have to pass just one element, you can pass it as a plain element as well: 1025 1026 $tm = new Template::Magic 1027 lookups => [\%my_hash] , 1028 markers => ['HTML_MARKERS' ] ; 1029 1030 # same thing less noisy 1031 $tm = new Template::Magic 1032 lookups => \%my_hash , 1033 markers => 'HTML' ; 1034 1035All the handlers in C<-*_handlers> I<(zone handlers, value handlers, output handlers, text handlers, post handlers)> receive the I<zone object> as $_[0] parameter. Besides, the I<text handlers> and the I<output handlers> receive also the processed text as $_[1] parameter. 1036 1037B<Note>: the old constructor arrays identifiers with the prepended '-' and/or the parameters passed as a reference to a hash are deprecated but still working: 1038 1039 # old style with '-flag' and brackets 1040 $tm = new Template::Magic 1041 { 1042 -markers => qw( < / > ) , 1043 -lookups => [ \%my_hash, $my_obj, 'main' ] , 1044 -zone_handlers => [ \&my_zone_handler, '_EVAL_' ] , 1045 -value_handlers => [ 'DEFAULT', \&my_value_handler ] , 1046 -text_handlers => sub {print lc $_[1]} , 1047 -output_handlers => sub {print uc $_[1]} , 1048 -post_handlers => \&my_post_handler , 1049 } ; 1050 1051=head3 paths 1052 1053Use this constructor array to supply a list of paths to search for templates. This list will be used when you pass a relative path as the template name. 1054 1055See L<find_file()|find_file ( template )> method for details about how the paths are searched. 1056 1057=head3 markers 1058 1059Use this constructor array to define the 3 I<label markers> - START_MARKER, END_MARKER_ID, END_MARKER - you want to use in your template. The C<markers> constructor array can contain a name of L<standard markers>, or a reference to an array containing the 3 explicit markers. 1060 1061If you want to use the default markers, just call the new() method without any C<markers> constructor array: 1062 1063 # default markers 1064 $tm = new Template::Magic; 1065 1066 # same but explicit extension name 1067 $tm = new Template::Magic 1068 markers => 'DEFAULT_MARKERS'; 1069 1070 # same but 3 explicit default markers 1071 $tm = new Template::Magic 1072 markers => [ '{', '/', '}' ] ; 1073 1074 # HTML markers extension name 1075 $tm = new Template::Magic 1076 markers => 'HTML_MARKERS' }; 1077 1078 # same but 3 explicit HTML markers 1079 $tm = new Template::Magic 1080 markers => [ qw( <!--{ / }--> ) ] ; 1081 1082 # custom explicit markers 1083 $tm = new Template::Magic 1084 markers => [ qw( __ END_ __ ) ] ; 1085 1086Since each element of the markers array is parsed as a regular expression as: C<qr/element/>, you can extend the markers beyond a static string marker. 1087 1088These markers: 1089 1090 # 3 weird explicit markers 1091 $tm = new Template::Magic 1092 markers => [ '<\d+<', '\W', '>' ]; 1093 1094will match these blocks labeled 'identifier': 1095 1096 <35<identifier> content of block <0<-identifier> 1097 <26<identifier> content of block <15<#identifier> 1098 1099You can also pass compiled RE: 1100 1101 # 3 weird explicit markers 1102 $start = qr/<\d+</ ; 1103 $end_ID = qr/\W/ ; 1104 $end = qr/>/ ; 1105 $tm = new Template::Magic 1106 markers => [ $start, $end_ID, $end ]; 1107 1108B<Note>: Remember that if the characters you chose as the markers have a special meaning in RE (e.g. the '[' and ']'), you need to escape them as you would do inside a pattern match. 1109 1110 # this would generate an error 1111 $tm = Template::Magic->new( markers => [ '[', '/', ']' ] ) 1112 1113 # you probably mean this 1114 $tm = Template::Magic->new( markers => [ '\[', '/', '\]' ] ) 1115 1116=head4 standard markers 1117 1118Template::Magic offers 3 standard markers: B<DEFAULT_MARKERS>, B<CODE_MARKERS> and B<HTML_MARKERS>: 1119 1120=over 1121 1122=item DEFAULT_MARKERS 1123 1124The default markers: 1125 1126 START MARKER: { 1127 END_MARKER_ID: / 1128 END_MARKER: } 1129 1130Example of block: 1131 1132 {identifier} content of the block {/identifier} 1133 1134=item CODE_MARKERS 1135 1136This markers are useful when you deal with templates which contain code, because they reduces the possible conflict with the content: 1137 1138 START MARKER: <- 1139 END_MARKER_ID: / 1140 END_MARKER: -> 1141 1142Example of block: 1143 1144 <-identifier-> content of the block <-/identifier-> 1145 1146=item HTML_MARKERS 1147 1148HTML-comment-like markers. If your output is a HTML text - or just because you prefer that particular look - you can use it instead of using the default markers. 1149 1150 START MARKER: <!--{ 1151 END_MARKER_ID: / 1152 END_MARKER: }--> 1153 1154Example of block: 1155 1156 <!--{identifier}--> content of the block <!--{/identifier}--> 1157 1158Usage: 1159 1160 $tm = new Template::Magic 1161 markers => 'HTML_MARKERS' ; 1162 1163The main advantages to use it are: 1164 1165=over 1166 1167=item * 1168 1169You can add labels and blocks and the template will still be a valid HTML file. 1170 1171=item * 1172 1173You can edit the HTML template with a WYSIWYG editor, keeping a consistent preview of the final output 1174 1175=item * 1176 1177The normal HTML comments will be preserved in the final output, while the labels will be wiped out. 1178 1179=back 1180 1181If you want to use the HTML handlers too, you could use Template::Magic::HTML. See L<Template::Magic::HTML> for details. 1182 1183=back 1184 1185See also L<"Redefine Markers"> 1186 1187=head3 lookups 1188 1189Use this constructor array to explicitly define where to look up the values in your code. This array can contain B<package names>, B<blessed objects> and B<hash references>. If no lookups construction array is passed, the package namespace of the caller will be used by default. 1190 1191With B<packages names> the lookup is done with all the IDENTIFIERS (variables and subroutines) defined in the package namespace. 1192 1193B<Note>: Please, notice that the lexical variables (those declared with C<my>) are unaccessible from outside the enclosing block, file, or eval, so don't expect that the lookup could work with these variables: it is a perl intentional restriction, not a limitation of this module. However, you could declare them with the old C<vars> pragma or C<our> declaration instead, and the lookup will work as expected. 1194 1195With B<blessed objects> the lookup is done with all the IDENTIFIERS (variables and methods) defined in the class namespace. B<Note>: Use this type of location when you want to call an object method from a template: the method will receive the blessed object as the first parameter and it will work as expected. 1196 1197With B<hash references> the lookup is done with the KEYS existing in the hash. 1198 1199If you want to make available all the identifiers of your current package, just call the constructor without any C<lookups> parameter: 1200 1201 # default lookup in the caller package 1202 $tm = new Template::Magic ; 1203 1204 # same thing but explicit 1205 $tm = new Template::Magic 1206 lookups => __PACKAGE__ ; 1207 1208B<Warning>: Template::Magic can be used to write sloppy code or very strict code, exactly as perl itself can. Magic lookups is a very handly feature for simple scripts, while it is not recommended for complex script where you should explicitly limit the lookups to some specific package or hash. 1209 1210If you want to keep unavailable some variable or subroutine from the template, you can pass just the reference of some hash containing just the identifiers used in the template. This is the best method to use the module IF you allow untrustworthy people to edit the template AND if you have any potentially dangerous subroutine in your code. (see L<"Allow untrustworthy people to edit the template">). 1211 1212 # lookup in %my_hash only 1213 $tm = new Template::Magic 1214 lookups => \%my_hash ; 1215 1216You can also define an arbitrary list of packages, references to hashes and blessed object as the lookup: the precedence of the lookup will be inherited from the order of the items passed, and the first found mach will return the value. 1217 1218B<Note>: If you have multiple symbols in your code that maches the label id in your template, don't expect any warning: to be fast, Template::Magic does not check your errors and consider OK the first symbol it founds. 1219 1220 # lookup in several locations 1221 $tm = new Template::Magic 1222 lookups => [ \%my_hash, 'My::Pack', \%my_other_hash ] ; 1223 1224In this example, the lookup will be done in C<%my_hash> first - if unsuccessful - it will be done in the C<My::Pack> package and - if unsuccessful - it will be done in C<%my_other_hash>. 1225 1226If you use Template::Magic inside another module, you can pass the blessed object as the location: 1227 1228 use Template::Magic; 1229 package Local::foo; 1230 sub new 1231 { 1232 my $s = bless {data=>'THE OBJECT DATA'}, shift; 1233 $$s{tm} = new Template::Magic 1234 lookups => $s; 1235 $s; 1236 } 1237 1238 sub method_triggered_by_lookup 1239 { 1240 my ($s, $zone) = @_; # correct object passed + zone object 1241 ... 1242 $$s{data}; 1243 } 1244 1245so that if some I<zone identifier> will trigger 'I<method_triggered_by_lookup>', it will receive the blessed object as the first parameter and it will work as expected. 1246 1247I<(see also L<Template::Magic::Zone/"lookup_process()">)>. 1248 1249=head4 Temporary Lookups 1250 1251You can also pass some temporary lookups along with the print(), nprint(), output(), noutput() methods (i.e. lookups that will be used only for one template processing). This capability is useful when you want to use the same object but you don't want to use the same lookups e.g. to have some sort of lookup inheritance as this: 1252 1253 $tm = new Template::Magic 1254 lookups => \%general_hash ; 1255 1256 # in sub 1 1257 $tm->nprint( template => '/path/to/template1' , 1258 lookups => \%special_hash1 ) ; 1259 # lookup done in %special_hash1 and then in %general_hash 1260 1261 # in sub 2 1262 $tm->nprint( template => '/path/to/template2' , 1263 lookups => \%special_hash2 ) ; 1264 # lookup done in %special_hash2 and then in %general_hash 1265 1266=head3 zone_handlers 1267 1268Use this constructor array to add handlers to manage the output generation before any other process (even before the C<lookup_process()>). The zone handlers are executed just after the creation of the new zone, so you can even bypass or change the way of calling the other processes. 1269 1270This constructor array can contain B<code references> and/or B<standard zone handlers names> (resulting in one or more code references: see L<standard zone handlers> for details. 1271 1272The default C<zone_handler> is undefined, so you must add explicitly any standard zone handler or your own handler in order to use it. 1273 1274 $tm = new Template::Magic 1275 zone_handlers => [ '_EVAL_' , 1276 '_EVAL_ATTRIBUTES' , 1277 'INCLUDE_TEXT' , 1278 \&my_handler ] ; 1279 1280B<Note>: If you write your own custom I<zone_handler>, remember that it must return a true value to end the C<zone_process>, or a false value to continue the C<zone_process>. In other words: if your I<zone_handler> has taken the control of the whole process it must return true, so the other processes (i.e. C<lookup_process> and C<value_process>) will be skipped, while if you want to continue the normal process your I<zone_handler> must return false. 1281 1282To simplify things you can import and use the constants C<NEXT_HANDLER> and C<LAST_HANDLER> that are more readable and simpler to remember (see L<"Constants">). 1283 1284(see also L<Template::Magic::Zone/"zone_process()">) 1285 1286=head4 standard zone handlers 1287 1288=over 1289 1290=item _EVAL_ 1291 1292This handler sets the C<value> property to the evalued result of the I<zone content> when the I<zone identifier> is equal to '_EVAL_' 1293 1294B<WARNING>: For obvious reasons you should use this zone handler ONLY if you are the programmer AND the designer. 1295 1296This handler is useful if you want a cheap way to embed perl code in the template. (see L<"Embed perl into a template">) 1297 1298=item _EVAL_ATTRIBUTES_ 1299 1300This handler sets the C<param> property to the evalued result of the I<zone attributes> 1301 1302B<WARNING>: For obvious reasons you should use this zone handler ONLY if you are the programmer AND the designer. 1303 1304This handler is useful if you want to pass some structure to a sub from the template without writing a parser: you will have the structure available in $z->param. (see L<"Pass a structure to a subroutine">) 1305 1306=item TRACE_DELETIONS 1307 1308This handler generates a diagnostic output for each zone that has not generated any output. It will output a string like <my_zone_id not found> or <my_zone_id found but empty> in place of the zone, so you can better understand what's going on. 1309 1310=item INCLUDE_TEXT 1311 1312This handler adds the possibility to include in the output a (probably huge) text file, without having to keep it in memory as a template, and without any other parsing. 1313 1314It works with the I<zone identifier> equal to 'INCLUDE_TEXT' and the I<zone attributes> equal to the file path to include. It passes each line in the file to the C<text_process> method and bypass all the other processs. 1315 1316(see L<"Include (huge) text files without memory charges">) 1317 1318B<Note>: Since this handler bypasses every other process, it is useful only for text output. If you need to include and parse a real template file see L<"Include and process a template file">. 1319 1320=back 1321 1322=head3 value_handlers 1323 1324Use this constructor array to explicitly define or modify the way the object finds the value in your code. 1325 1326This constructor array can contain B<code references> and/or B<standard value handlers names> (resulting in one or more code references: see L<standard value handlers> for details). 1327 1328If you don't pass any C<value_handler> constructor array, the default will be used: 1329 1330 $tm = new Template::Magic; 1331 1332 # means 1333 $tm = new Template::Magic 1334 value_handler => 'DEFAULT' ; 1335 1336 # that expicitly means 1337 $tm = new Template::Magic 1338 value_handlers => [ qw( SCALAR REF CODE ARRAY 1339 HASH OBJECT ) ] ; 1340 1341Where 'DEFAULT', 'SCALAR', 'REF', 'CODE', 'ARRAY', 'HASH', 'OBJECT' are I<standard value handlers names>. 1342 1343You can add, omit or change the order of the elements in the array, fine tuning the behaviour of the object. 1344 1345 $tm = new Template::Magic 1346 value_handlers => [ 'DEFAULT', \&my_handler ] ; 1347 1348 # that explicitly means 1349 $tm = new Template::Magic 1350 value_handlers => [ 'SCALAR' , 1351 'REF' , 1352 'CODE' , 1353 'ARRAY' , 1354 'HASH' , 1355 'OBJECT' 1356 \&my_handler ] ; 1357 1358 # or you can add, omit and change the order of the handlers 1359 $tm = new Template::Magic 1360 value_handlers => [ 'SCALAR', 1361 'REF', 1362 \&my_handler, 1363 'ARRAY', 1364 'HASH', 1365 'OBJECT' 1366 ] ; 1367 1368B<Note>: If you write your own custom I<value_handler>, remember that it must return a true value to end the C<value_process>, or a false value to continue the C<value_process>. 1369 1370To simplify things you can import and use the constants C<NEXT_HANDLER> and C<LAST_HANDLER> that are more readable and simpler to remember (see L<"Constants">). 1371(see also L<Template::Magic::Zone/"value_process()">) 1372 1373=head4 standard value handlers 1374 1375=over 1376 1377=item DEFAULT 1378 1379This is the shortcut for the default collection of value handlers that defines the following handlers: 1380 1381 SCALAR 1382 REF 1383 CODE 1384 ARRAY 1385 HASH 1386 OBJECT 1387 1388All the default values are based on a condition that checks the found value. 1389 1390=item SCALAR 1391 1392A I<SCALAR> value sets the C<output> property to the value, and pass it to the C<output_process> ending the C<value_process> method. 1393 1394=item REF 1395 1396A I<REFERENCE> value (SCALAR or REF) sets the C<value> property to the dereferenced value and start again the C<value_process()> method 1397 1398=item CODE 1399 1400A I<CODE> value sets the C<value> property to the result of the execution of the code and start again the C<value_process()> method. The subroutine will receive the I<zone object> as a parameter. 1401 1402If you want to avoid the execution of code, triggered by some identifier, just explicitly omit this handler 1403 1404 $tm = new Template::Magic 1405 value_handlers => [ qw( SCALAR REF ARRAY 1406 HASH OBJECT ) ] ; 1407 1408See L<"Avoid unwanted executions"> for details. See also L<"Pass parameters to a subroutine"> 1409 1410=item ARRAY 1411 1412This handler generates a loop, merging each value in the array with the I<zone content> and replacing the I<zone> with the sequence of the outputs. I<(see L<"Build a loop">, L<"Build a nested loop"> and L<"Build a simple loop"> for details)>. 1413 1414=item HASH 1415 1416A B<HASH> value type will set that HASH as a B<temporary lookup> for the I<zone>. Template::Magic first uses that hash to look up the identifiers contained in the block; then, if unsuccessful, it will search into the other elements of the C<lookups> constructor array. This handler is usually used in conjunction with the ARRAY handler to generate loops. I<(see L<"Build a loop"> and L<"Build a nested loop"> for details)>. 1417 1418=item OBJECT 1419 1420An B<OBJECT> value type causes the object itself to be used as the temporary lookup for the zone (usually a block ;-). First Template::Magic will try all the label contained in the block as a method of the object; if unsuccessful, it will search into the other elements of the C<lookups> constructor array. 1421 1422=back 1423 1424=head3 output_handlers 1425 1426If you need to change the way the output is processed, you can add your own handler. 1427 1428This constructor array can contain B<code references> and/or B<standard output handlers names> (resulting in one or more code references: see L<standard output handlers> for details). 1429 1430If you want to use the default I<output handler>, just call the new() method without any C<output_handler> constructor array: 1431 1432 $tm = new Template::Magic; 1433 1434 # this means (if you are using print() method) 1435 $tm = new Template::Magic 1436 output_handler => 'DEFAULT_PRINT_HANDLER'; 1437 1438 # or means (if you are using output() method) 1439 $tm = new Template::Magic 1440 output_handler => 'DEFAULT_OUTPUT_HANDLER' ; 1441 1442 1443B<Note>: If you write your own custom I<output_handler>, remember that it must return a true value to end the C<output_process>, or a false value to continue the C<output_process>. 1444 1445To simplify things you can import and use the constants C<NEXT_HANDLER> and C<LAST_HANDLER> that are more readable and simpler to remember (see L<"Constants">). 1446 1447(see also L<Template::Magic::Zone/"output_process()">) 1448 1449=head4 standard output handlers 1450 1451=over 1452 1453=item DEFAULT_PRINT_HANDLER 1454 1455This handler is set by default by the C<print()> method. It receives and print each chunk of output that comes from the output generation. 1456 1457This is the code of the print handler: 1458 1459 sub{ print $_[1] if defined $_[1]; NEXT_HANDLER} 1460 1461=item DEFAULT_OUTPUT_HANDLER 1462 1463Deprecated handler. Use the C<DEFAULT_PRINT_HANDLER> instead. 1464 1465=back 1466 1467=head3 text_handlers 1468 1469Use this constructor array only if you want to process the text coming from the template in a different way from the text coming from the code. 1470 1471This constructor array can contain B<code references> and/or B<standard output handlers names> (resulting in one or more code references: see L<standard output handlers> for details). 1472 1473If you don't set any I<text handler>, the current I<output handlers> will be used. 1474 1475B<Note>: If you write your own custom I<text_handler>, remember that it must return a true value to end the C<text_process>, or a false value to continue the C<text_process>. 1476 1477To simplify things you can import and use the constants C<NEXT_HANDLER> and C<LAST_HANDLER> that are more readable and simpler to remember (see L<"Constants">). 1478 1479(see also L<Template::Magic::Zone/"text_process()">) 1480 1481=head3 post_handlers 1482 1483Use this constructor array only if you want to clean up or log processes just before a zone goes out of scope. (see also L<Template::Magic::Zone/"post_process()">) 1484 1485B<Note>: This constructor array can contain B<code references>. 1486 1487B<Note>: If you write your own custom I<post_handler>, remember that it must return a true value to end the C<post_process>, or a false value to continue the C<post_process>. 1488 1489To simplify things you can import and use the constants C<NEXT_HANDLER> and C<LAST_HANDLER> that are more readable and simpler to remember (see L<"Constants">). 1490 1491(see also L<Template::Magic::Zone/"post_process()">) 1492 1493=head3 options 1494 1495Use this constructor array to pass some boolean value like 'cache' or 'no_cache'. 1496 1497=over 1498 1499=item cache / no_cache 1500 1501Control the caching of the templates structures. 'cache' is the default, so you don't need to explicitly use it in order to cache the template. Use 'no_cache' to avoid the caching. 1502 1503=back 1504 1505=head3 container_template 1506 1507You can pass a generic template which will be used as a sort of frame for all the printed templates. It can be set to one I<template> parameter that can be a reference to a SCALAR content, a path to a template file or a filehandle. 1508 1509(See L<"Surrounding the output with a container template">) 1510 1511=head3 Constants 1512 1513If you write your own handler you can find useful a couple of constants that you can import: 1514 1515=over 1516 1517=item * NEXT_HANDLER (false) 1518 1519=item * LAST_HANDLER (true) 1520 1521=back 1522 1523 use Template::Magic qw(NEXT_HANDLER LAST_HANDLER); 1524 1525 sub my_handler 1526 { 1527 my ($zone) = @_ ; 1528 if (some_condition) 1529 { 1530 do_something ; 1531 LAST_HANDLER ; 1532 } 1533 else 1534 { 1535 NEXT_HANDLER ; 1536 } 1537 } 1538 1539 1540=head1 HOW TO... 1541 1542This section is oriented to suggest you specific solutions to specific needs. If you need some more help, feel free to send me a message. 1543 1544=head2 Understand the output generation 1545 1546By default the output will be generated by the found I<value type>, that means that differents value types will cause different behaviour in generating the output. In details: 1547 1548=over 1549 1550=item * 1551 1552A B<SCALAR> value type will B<replace> the I<zone> with the scalar value. 1553 1554=item * 1555 1556A B<REFERENCE> value will be B<dereferenced>, and the value returned will be checked again to apply an appropriate handler 1557 1558=item * 1559 1560A B<CODE> value type will be B<executed>, and the value returned will be checked again to apply an appropriate handler 1561 1562=item * 1563 1564An B<ARRAY> value type will B<generate a loop>, merging each value in the array with the I<zone content> and replacing the I<zone> with the sequence of the outputs. 1565 1566=item * 1567 1568A B<HASH> value type will set that HASH as a B<temporary lookup> for the I<zone>. Template::Magic first uses that hash to look up the identifiers contained in the block; then, if unsuccessful, it will search into the other elements of the C<lookups> constructor array. 1569 1570=item * 1571 1572An B<OBJECT> value type causes the object itself to be used as the temporary lookup for the zone (usually a block ;-). First Template::Magic will try all the label contained in the block as a method of the object; if unsuccessful, it will search into the other elements of the C<lookups> constructor array. 1573 1574= item * 1575 1576Finally, if no value are found in the code, the I<zone> will be B<deleted>. 1577 1578=back 1579 1580These are some examples of default value handlers: 1581 1582The same template: '{block}|before-{label}-after|{/block}' 1583 1584 ... with these values... ...produce these outputs 1585 ------------------------------------------------------------------------ 1586 $label = 'THE VALUE'; > 1587 $block = undef; 1588 ------------------------------------------------------------------------ 1589 $label = 'THE VALUE'; > NEW CONTENT 1590 $block = 'NEW CONTENT'; 1591 ------------------------------------------------------------------------ 1592 $label = 'THE VALUE'; > |before-THE VALUE-after| 1593 $block = {}; 1594 ------------------------------------------------------------------------ 1595 $label = undef; > |before--after| 1596 $block = {}; 1597 ------------------------------------------------------------------------ 1598 $label = 'THE VALUE'; > |before-NEW VALUE-after| 1599 %block = (label=>'NEW VALUE'); 1600 ------------------------------------------------------------------------ 1601 $label = 'THE VALUE'; > |before-NEW VALUE-after| 1602 $block = {label=>'NEW VALUE'}; 1603 ------------------------------------------------------------------------ 1604 $label = 'THE VALUE'; > NEW CONTENT|before-THE VALUE-after| 1605 @block = ('NEW CONTENT', |before-NEW VALUE-after| 1606 {}, 1607 {label=>'NEW VALUE'}); 1608 ------------------------------------------------------------------------ 1609 $label = 'THE VALUE'; > NEW CONTENT|before-THE VALUE-after| 1610 $block = ['NEW CONTENT', |before-NEW VALUE-after| 1611 {}, 1612 {label=>'NEW VALUE'}]; 1613 ------------------------------------------------------------------------ 1614 sub label { scalar localtime } > |before-Tue Sep 10 14:52:24 2002- 1615 $block = {}; after| 1616 ------------------------------------------------------------------------ 1617 $label = 'THE VALUE'; > |BEFORE-{LABEL}-AFTER| 1618 sub block { uc shift } 1619 ------------------------------------------------------------------------ 1620 package Local::Foo 1621 sub new {bless {}, shift} 1622 sub label {my $s = shift; 'NEW VALUE from '.$s} 1623 1624 package main 1625 $block = Local::Foo->new 1626 > |before-NEW VALUE from Local::Foo=HASH(0x1957934)-after| 1627 ------------------------------------------------------------------------ 1628 1629Different combinations of I<values> and I<zones> can easily produce complex outputs: see the other topics in this section. 1630 1631=head2 Use template directories 1632 1633You can set the $ENV{TEMPLATE_MAGIC_ROOT} or use the paths constructor array to pass a list of directories to use when searching the template. 1634 1635See L<find_file()|find_file ( template )> method for details about how the paths are searched. 1636 1637=head2 Include and process a template file 1638 1639To include a file in a template use the I<INCLUDE_TEMPLATE> label passing the file path as the label attribute: 1640 1641 {INCLUDE_TEMPLATE /temp/footer.html} 1642 1643The F<'/temp/footer.html'> file will be included in place of the label and it will be processed (and automatically cached) as usual. 1644 1645B<WARNING>: An icluded template is processed as it was a complete template, this means that a I<block> should be always ended with an I<end label> in the same template. In other words I<blocks> cannot cross the boundary of the file they belong to, or unpredictable behaviours could occur. 1646 1647=head2 Conditionally include and process a template file 1648 1649Sometimes it may be useful to include a template only if a condition is true. To do so you can use the $zone->include_template method that works exacly as the I<INCLUDE_TEMPLATE> label, but it is triggered from inside your code instead of the template itself: 1650 1651 sub include_if_some_condition 1652 { 1653 my $zone = shift 1654 if ( some_condition ) 1655 { 1656 return $zone->include_template('/path/to/template') 1657 } 1658 else # may be you want just return '' 1659 { 1660 return 'template not included' 1661 } 1662 } 1663 1664The template: 1665 1666 this is the template {include_if_some_condition} end template 1667 1668=head2 Surrounding the output with a container template 1669 1670Sometime you may have headers and footers to add to a single or all the templates you want to print. You can use the 'container_template' argument, to pass the container template to the object constructor or to the C<noutput> or C<nprint> methods: 1671 1672 # will work with all the outputs 1673 $tm = new Template::Magic 1674 container_template => '/path/to/container_template'; 1675 1676 $tm->print('/path/to/template'); 1677 1678 # will work just for a single output 1679 $tm = new Template::Magic 1680 1681 $tm->nprint(container_template => '/path/to/container_template', 1682 template => '/path/to/template' ); 1683 1684The container template file is a regular template, but MUST include an INCLUDE_TEMPLATE label B<without any attribute>: the original template will be used as the included template: 1685 1686 An header 1687 {INCLUDE_TEMPLATE} 1688 a footer 1689 1690The template file: 1691 1692 The template content 1693 1694The output: 1695 1696 An header 1697 The template content 1698 a footer 1699 1700=head2 Include (huge) text files without memory charges 1701 1702To include in the output a (probably huge) text file, without having to keep it in memory as a template, and without any other parsing, add the L<INCLUDE_TEXT> I<zone handler> and add a label with the I<zone identifier> equal to 'INCLUDE_TEXT' and the I<zone attributes> equal to the file path to include. 1703 1704 $tm = new Template::Magic 1705 zone_handlers => 'INCLUDE_TEXT' ; 1706 1707The template label: 1708 1709 {INCLUDE_TEXT /path/to/text/file} 1710 1711B<Note>: do not use quotes! 1712 1713=head2 Redefine Markers 1714 1715=over 1716 1717=item by explicitly define the markers constructor parameter 1718 1719 # redefine the markers as needed 1720 $tm = new Template::Magic 1721 markers => [ qw( <- / -> ) ] ; 1722 1723=item by using standard markers 1724 1725The standard installation comes with a HTML friendly L<"standard markers"> that implements a HTML-comment-like syntax. If your output is an HTML text - or just because you prefer that particular look - you can use it instead of using the default markers. 1726 1727 $tm = new Template::Magic 1728 markers => 'HTML_MARKERS' ; 1729 1730 # that means 1731 $tm = new Template::Magic 1732 markers => [ qw( <!--{ / }--> ) ] ; 1733 1734=back 1735 1736See L<"markers"> constructor array for details. 1737 1738=head2 Setup a template 1739 1740A quick way to setup a template in 4 simple steps is the following: 1741 1742=over 1743 1744=item 1 Prepare an output 1745 1746Prepare a complete output as your code could print. Place all the static items of your output where they should go, place placeholders (any runtime value that your code would supply) where they should go and format everything as you want 1747 1748=item 2 Choose names 1749 1750Choose meaningful names (or variables and subroutines names if you already have a code) for labels and blocks 1751 1752=item 3 Insert single labels 1753 1754Find the dynamic items in the template and replace them with a label, or if you want to keep them as visible placeholders, transform each one of them into a block 1755 1756=item 4 Define blocks 1757 1758If you have any area that will be repeated by a loop or that will be printed just under certain conditions transform it into a block. 1759 1760=back 1761 1762=head2 Setup placeholders 1763 1764These are a couple of templates that use a HTML friendly sintax. The output will be the same for both templates, with or without placeholders: the difference is the way you can look at the template. 1765 1766=over 1767 1768=item template without placeholders 1769 1770 <p><hr> 1771 Name: <b style="color:blue"><!--{name}--></b><br> 1772 Surname: <b style="color:blue"><!--{surname}--></b> 1773 <hr></p> 1774 1775This is what you would see in a WYSIWYG editor: I<(you should be using a browser to see the example below this line)> 1776 1777=for html 1778<p><hr>Name: <b style="color:blue"><!--{name}--></b><br> 1779Surname: <b style="color:blue"><!--{surname}--></b><hr></p> 1780 1781=item template with placeholders 1782 1783The placeholders "John" and "Smith" are included in blocks and will be replaced by the actual values of 'name' and 'surname' from your code. 1784 1785 <p><hr> 1786 Name: <b style="color:blue"><!--{name}-->John<!--{/name}--></b><br> 1787 Surname: <b style="color:blue"><!--{surname}-->Smith<!--{/surname}--></b> 1788 <hr></p> 1789 1790This is what you would see in a WYSIWYG editor: I<(you should be using a browser to see the example below this line)> 1791 1792=for html 1793<p><hr>Name: <b style="color:blue"><!--{name}-->John<!--{/name}--></b><br> 1794Surname: <b style="color:blue"><!--{surname}-->Smith<!--{/surname}--></b><hr></p> 1795 1796=back 1797 1798=head2 Setup simulated areas 1799 1800If you want to include in your template some area only for design purpose I<(for example to see, right in the template, how could look a large nested loop)>, just transform it into a block and give it an identifier that will never be defined in your code. 1801 1802 {my_simulated_area} this block simulates a possible output 1803 and it will never generate any output {/my_simulated_area} 1804 1805=head2 Setup labeled areas 1806 1807If you want to label some area in your template I<(for example to extract the area to mix with another template)>, just transform it into a block and give it an identifier that will always be defined in your code. A convenient way to do so is to define a reference to an empty hash. This will generate the output of the block and (since the hash does not contain any keys) the lookup will fallback to the I<containers> zones and the I<lookups> locations. 1808 1809=over 1810 1811=item the code 1812 1813 $my_labeled_area = {} ; # a ref to an empty hash 1814 1815=item the template 1816 1817 {my_labeled_area} 1818 this block will always generate an output 1819 {/my_labeled_area} 1820 1821=back 1822 1823=head2 Build a loop 1824 1825=over 1826 1827=item the template 1828 1829A loop is represented by a block, usually containing labels: 1830 1831 A loop: 1832 {my_loop}------------------- 1833 Date: {date} 1834 Operation: {operation} 1835 {/my_loop}------------------- 1836 1837=item the code 1838 1839You should have some array of hashes (or a reference to) defined somewhere: 1840 1841 $my_loop = [ 1842 { 1843 date => '8-2-02', 1844 operation => 'purchase' 1845 }, 1846 { 1847 date => '9-3-02', 1848 operation => 'payment' 1849 } 1850 ] ; 1851 1852=item the output 1853 1854 A loop: 1855 ------------------- 1856 Date: 8-2-02 1857 Operation: purchase 1858 ------------------- 1859 Date: 9-3-02 1860 Operation: payment 1861 ------------------- 1862 1863=back 1864 1865=head2 Build a nested loop 1866 1867=over 1868 1869=item the template 1870 1871A nested loop is represented by a block nested into another block: 1872 1873 A nested loop: 1874 {my_nested_loop}------------------- 1875 Date: {date} 1876 Operation: {operation} 1877 Details:{details} 1878 - {quantity} {item}{/details} 1879 {/my_nested_loop}------------------- 1880 1881Notice that the block I<'details'> is nested into the block I<'my_nested_loop'>. 1882 1883=item the code 1884 1885You should have some array nested into some other array, defined somewhere: 1886 1887 # a couple of nested "for" loops may produce this: 1888 $my_nested_loop = [ 1889 { 1890 date => '8-2-02', 1891 operation => 'purchase', 1892 details => [ 1893 { 1894 quantity => 5, 1895 item => 'balls' 1896 }, 1897 { 1898 quantity => 3, 1899 item => 'cubes' 1900 }, 1901 { 1902 quantity => 6, 1903 item => 'cones' 1904 } 1905 ] 1906 }, 1907 { 1908 date => '9-3-02', 1909 operation => 'payment', 1910 details => [ 1911 { 1912 quantity => 2, 1913 item => 'cones' 1914 }, 1915 { quantity => 4, 1916 item => 'cubes'} 1917 ] 1918 } 1919 ] ; 1920 1921Notice that the value of the keys I<'details'> are a reference to an array of hashes. 1922 1923=item the output 1924 1925 A nested loop: 1926 ------------------- 1927 Date: 8-2-02 1928 Operation: purchase 1929 Details: 1930 - 5 balls 1931 - 3 cubes 1932 - 6 cones 1933 ------------------- 1934 Date: 9-3-02 1935 Operation: payment 1936 Details: 1937 - 2 cones 1938 - 4 cubes 1939 ------------------- 1940 1941=back 1942 1943=head2 Build a simple loop 1944 1945This is a new feature implemented in Template::Magic 1.32, that allows the direct handling of array items in loops (i.e. you can use an array of strings instead of an array of hashes containing a named string). 1946 1947When the loop contains just a label, you can also directly use the items of any array, eventually using also the relative index number: 1948 1949=over 1950 1951=item the code 1952 1953You should have some array defined somewhere: 1954 1955 $my_loop = [ qw( ball cube cone ) ] ; 1956 1957=item the template 1958 1959A loop is represented by a block, usually containing labels. This loop defines as 'product' the label representing each array item, the progressive count as 'line_number' and the starting count at 1: 1960 1961 A loop: 1962 {my_loop OF product line_number 1}------------------- 1963 {line_number} - Product: {product} 1964 {/my_loop}------------------- 1965 1966=item the output 1967 1968 A loop: 1969 ------------------- 1970 1 - Product: ball 1971 ------------------- 1972 2 - Product: cube 1973 ------------------- 1974 3 - Product: cone 1975 ------------------- 1976 1977=back 1978 1979B<Note>: any loop that directly uses the values of any array, can be written as: 1980 1981=over 1982 1983=item {my_array} 1984 1985this is used only when the array items are reference to hashes (see L<"Build a loop"> or L<"Build a nested loop">) 1986 1987=item {my_array OF anything index 1} 1988 1989this defines as 'anything' the label representing each array item, the progressive count as 'index' and the starting count will start at 1 1990 1991=item {my_array OF anything index} 1992 1993if you omit the starting count value, it will start at 0 1994 1995=item {my_array OF anything} 1996 1997if you don't use any progressive count inside the block you may omit it 1998 1999=item {my_array anything} 2000 2001you can also omit the 'OF' (case insensitive) keyword in all the above cases 2002 2003=back 2004 2005=head2 Process (huge) loops iteration by iteration 2006 2007Usually a loop is built just by an array of hashes value (see L<"Build a loop">). This means that you have to fill an array with all the hashes BEFORE the process starts. In normal situations (i.e. the array contains just a few hashes) this is not a problem, but if the array is supposed to contain a lot of hashes, it could be more efficient by creating each hash just DURING the process and not BEFORE it (i.e. without storing it in any array). 2008 2009For example imagine that in the L<"Build a loop"> example, the array comes from a huge file like this: 2010 2011 8-2-02|purchase 2012 9-3-02|payment 2013 ... some hundred lines 2014 2015You could generate the output line by line with a simple sub like this: 2016 2017 sub my_loop 2018 { 2019 my ($z) = @_ ; 2020 open FILE, '/path/to/data/file' ; 2021 while (<FILE>) # for each line of the file 2022 { 2023 chomp ; 2024 my $line_hash ; 2025 @$line_hash{'date', 'operation'} = split /\|/ ; # create line hash 2026 $z->value = $line_hash ; # set the zone value 2027 $z->value_process() ; # process the value 2028 } 2029 } 2030 2031This way you don't waste memory to store the data for all the iteration into the array: you just use the memory needed for one iteration at a time. 2032 2033=head2 Setup an if-else condition 2034 2035=over 2036 2037=item the template 2038 2039An if-else condition is represented with 2 blocks 2040 2041 {OK_block}This is the OK block, containig {a_scalar}{/OK_block} 2042 {NO_block}This is the NO block{/NO_block} 2043 2044=item the code 2045 2046Remember that a block will be deleted if the lookup of the identifier returns the UNDEF value, so your code will determine what block will generate output (defined identifier) and what not (undefined identifier). 2047 2048 if ($OK) { $OK_block = {a_scalar => 'A SCALAR VARIABLE'} } 2049 else { $NO_block = {} } 2050 2051Same thing here: 2052 2053 $a_scalar = 'A SCALAR VARIABLE'; 2054 $OK ? $OK_block={} : $NO_block={}; 2055 2056=item the output 2057 2058A true C<$OK> would leave undefined C<$NO_block>, so it would produce this output: 2059 2060 This is the OK block, containig A SCALAR VARIABLE 2061 2062A false $OK would leave undefined C<$OK_block>, so it would produce this output: 2063 2064 This is the NO block 2065 2066Notice that C<$OK_block> and C<$NO_block> should not return a SCALAR value, that would replace the whole block with the value of the scalar. 2067 2068=back 2069 2070 2071=head2 Use the NOT_* blocks 2072 2073This is a new feature implemented in Template::Magic 1.2, that allows to simplify the if-else handling for any zone. It is intended to be used only in such case (if-else), and in such order (first the * block and next the NOT_* block); for any other use, please refer to L<"Setup an if-else condition">. 2074 2075For any zone you can use a NOT_* zone (where '*' stands for the zone id) which will automatically be printed if the zone is not printed, or wiped out if the zone is printed. 2076 2077The above example could be written also this way: 2078 2079=over 2080 2081=item the template 2082 2083 {OK_block}This is the OK block, containig {a_scalar}{/OK_block} 2084 {NOT_OK_block}This is the NOT_OK_block, containig {a_scalar}, 2085 and printed automatically if the OK_block will not be printed 2086 {/NOT_OK_block} 2087 2088=item the code 2089 2090 $a_scalar = 'A SCALAR VARIABLE'; 2091 $OK_block = any_condition() ? {} : '' 2092 2093=item the output 2094 2095A true C<any_condition()> whould set the C<$OK_block> to an empty hash reference, thus printing 2096 2097 This is the OK block, containig A SCALAR VARIABLE 2098 2099While a false C<any_condition()> whould wipe out the C<OK_block>, thus automatically printing the C<NOT_OK_block>. 2100 2101 This is the NOT_OK_block, containig A SCALAR VARIABLE, 2102 and printed automatically if the OK_block will not be printed 2103 2104=back 2105 2106=head2 Setup a switch condition 2107 2108=over 2109 2110=item the template 2111 2112A simple switch (if-elsif-elsif) condition is represented with multiple blocks: 2113 2114 {type_A}type A block with {a_scalar_1}{/type_A} 2115 {type_B}type B block with {a_scalar_2}{/type_B} 2116 {type_C}type C block with {a_scalar_1}{/type_C} 2117 {type_D}type D block with {a_scalar_2}{/type_D} 2118 2119=item the code 2120 2121Your code will determine what block will generate output (defined identifier) and what not (undefined identifier). In the following example, value of C<$type> will determine what block will produce output, then the next line will define C<$type_C> using a symbolic reference: 2122 2123 $type = 'type_C'; 2124 $$type = { a_scalar_1 => 'THE SCALAR 1', 2125 a_scalar_2 => 'THE SCALAR 2' }; 2126 2127Same thing yet but with a different programming style: 2128 2129 $a_scalar_1 = 'THE SCALAR 1'; 2130 $a_scalar_2 = 'THE SCALAR 2'; 2131 $type = 'type_D'; 2132 $$type = {}; 2133 2134Same thing without using any symbolic reference: 2135 2136 $type = 'type_D'; 2137 $my_hash{$type} = { a_scalar_1 => 'THE SCALAR 1', 2138 a_scalar_2 => 'THE SCALAR 2' }; 2139 $tm = new Template::Magic 2140 lookups => \%my_hash ; 2141 2142=item the output 2143 2144A C<$type> set to 'type_C' would produce this output: 2145 2146 type C block with THE SCALAR 1 2147 2148A C<$type> set to 'type_D' would produce this output: 2149 2150 type D block with THE SCALAR 2 2151 2152=back 2153 2154=head2 Pass parameters to a subroutine 2155 2156Template::Magic can execute subroutines from your code: when you use a zone identifier that matches with a subroutine identifier, the subroutine will receive the I<zone object> as a parameters and will be executed. This is very useful when you want to return a modified copy of the template content itself, or if you want to allow the designer to pass parameter to the subroutines. 2157 2158This example show you how to allow the designer to pass some parameters to a subroutine in your code. The 'matrix' sub, used in the example, receives the parameters written in the template and generates just a table filled of 'X'. 2159 2160=over 2161 2162=item the template 2163 2164 {matrix}5,3{/matrix} 2165 2166The content of 'matrix' block ('5,3') is used as parameter 2167 2168=item the code 2169 2170 sub matrix 2171 { 2172 my ($zone) = @_; 2173 my ($column, $row) = split ',' , $zone->content; # split the parameters 2174 my $out; 2175 for (0..$row-1) {$out .= 'X' x $column. "\n"}; 2176 $out; 2177 } 2178 2179The sub 'matrix' receive the reference to the I<zone object>, and return the output for the block 2180 2181=item the output 2182 2183 XXXXX 2184 XXXXX 2185 XXXXX 2186 2187=back 2188 2189The same example with named parameters, could be written as follow: 2190 2191=over 2192 2193=item the template 2194 2195 {matrix columns => 5, rows => 3} 2196 2197The attributes string of 'matrix' label (' columns => 5, rows => 3') is used as parameter 2198 2199=item the code 2200 2201 sub matrix 2202 { 2203 my ($zone) = shift; 2204 my $attributes = $zone->attributes; 2205 $attributes =~ tr/ //d; # no spaces 2206 my %attr = split /=>|,/, $attributes; # split the parameters 2207 my $out; 2208 for (0..$attr{rows}-1) {$out .= 'X' x $attr{columns} . "\n"}; 2209 $out; 2210 } 2211 2212The sub 'matrix' receive the reference to the I<zone object>, and return the output for the block 2213 2214=item the output 2215 2216 XXXXX 2217 XXXXX 2218 XXXXX 2219 2220=back 2221 2222=head2 Pass a structure to a subroutine 2223 2224You can use the '_EVAL_ATTRIBUTES_' zone handler to pass complex named structures to a subroutine. 2225 2226A simple example that use the '_EVAL_ATTRIBUTES_' zone handler could be: 2227 2228 $tm = new Template::Magic 2229 markers => ['<<', '/', '>>'] , # to avoid conflict 2230 zone_handlers => '_EVAL_ATTRIBUTES_' ; 2231 2232This is a possible example of template: 2233 2234 text <<my_sub {color => 'red', quantity => 2}>> text 2235 2236The '_EVAL_ATTRIBUTES_' zone handler set the C<param> property to the evalued I<attributes string> C<< {color => 'red', quantity => 2} >> in the template, so you can use it directly in your sub: 2237 2238 sub my_sub 2239 { 2240 my ($z) = @_ ; 2241 'The color is '. $z->param->{color} 2242 . ' the quantity is '. $z->param->{quantity} 2243 } 2244 2245B<WARNING>: You should use '_EVAL_ATTRIBUTES_' handler ONLY if you are the programmer AND the designer. 2246 2247=head2 Use subroutines to rewrite links 2248 2249If you use a block identifier that matches with a subroutine identifier, the subroutine will receive the content of the block as a single parameter and will be executed. This is very useful when you want to return a modified copy of the template content itself. 2250 2251A typical application of this capability is the template of a HTML table of content that point to several template files. You can use the capabilities of your favourite WYSIWYG editor to easily link each menu in the template with each template file. By doing so you will generate a static and working HTML file, linked with the other static and working HTML template files. This will allow you to easily check the integrity of your links, and preview how the links would work when utilized by your program. 2252 2253Then a simple C<modify_link> subroutine - defined in your program - will return a self-pointing link that will be put in the output in place of the static link. See the example below: 2254 2255=over 2256 2257=item the template 2258 2259 <p><a href="<!--{modify_link}-->add.html<!--{/modify_link}-->">Add Item 2260 </a></p> 2261 <p> 2262 <a href="<!--{modify_link}-->update.html<!--{/modify_link}-->">Update Item 2263 </a></p> 2264 <p> 2265 <a href="<!--{modify_link}-->delete.html<!--{/modify_link}-->">Delete Item 2266 </a></p> 2267 2268Working links pointing to static templates files (useful for testing and preview purpose, without passing through the program) 2269 2270=item the code 2271 2272 sub modify_link 2273 { 2274 my ($zone) = shift; 2275 my ($content) = $zone->content; 2276 $content =~ m|([^/]*).html$|; 2277 return '/path/to/myprog.cgi?action='.$content; 2278 } 2279 2280=item the output 2281 2282 <p><a href="/path/to/myprog.cgi?action=add">Add Item</a></p> 2283 <p><a href="/path/to/myprog.cgi?action=update">Update Item</a></p> 2284 <p><a href="/path/to/myprog.cgi?action=delete">Delete Item</a></p> 2285 2286Working links pointing to your program, defining different query strings. 2287 2288See also L<"Pass parameters to a subroutine">. 2289 2290=back 2291 2292=head2 Prepare the identifiers description list 2293 2294If you have to pass to a webmaster the description of every identifier in your program utilized by any label or block, Template::Magic can help you by generating a pretty formatted list of all the identifiers (from labels and blocks) present in any output printed by your program. Just follow these steps: 2295 2296=over 2297 2298=item 1 Add the following line anywhere before printing the output: 2299 2300 $tm->ID_list; 2301 2302=item 2 Capture the outputs of your program 2303 2304Your program will run exactly the same way, but instead of print the regular outputs, it will print just a pretty formatted list of all the identifiers present in any output. 2305 2306=item 3 Add the description 2307 2308Add the description of each label and block to the captured output and give it to the webmaster. 2309 2310=back 2311 2312=head2 Allow untrustworthy people to edit the template 2313 2314F<Magic.pm> does not use any eval() statement and the allowed characters for identifiers are only alphanumeric C<(\w+)>, so even dealing with tainted templates it should not raise any security problem that you wouldn't have in your program itself. 2315 2316=head3 Avoid unwanted executions 2317 2318This module can execute the subroutines of your code whenever it matches a label or block identifier with the subroutine identifier. Though unlikely, it is possible in principle that someone (only if allowed to edit the template) sneaks the correct identifier from your code, therefore, if you have any potentially dangerous subroutine in your code, you should restrict this capability. To do this, you can omit the C<CODE> value handler, or pass only explicit locations to the C<new()> method. 2319 2320=over 2321 2322=item potentially unsafe code 2323 2324 sub my_potentially_dangerous_sub { unlink 'database_file' }; 2325 $name = 'John'; 2326 $surname = 'Smith'; 2327 2328 # automatic lookup in __PACKAGE__ namespace 2329 $tm = new Template::Magic ; 2330 2331With this code, a malicious person allowed to edit the template could add the label I<{my_potentially_dangerous_sub}> in the template and that label would trigger the deletion of 'database_file'. 2332 2333=item code with subs_execution disabled 2334 2335Just explicitly omit the C<CODE> value handler when you create the object, so no sub will be executed: 2336 2337 $tm = new Template::Magic 2338 value_handler => [ qw( SCALAR REF ARRAY HASH ) ] ; 2339 2340=item code with restricted lookups 2341 2342 sub my_potentially_dangerous_sub { unlink 'database_file' }; 2343 %my_restricted_hash = ( name => 'John', surname => 'Smith' ); 2344 2345 # lookup in %my_restricted_hash only 2346 $tm = new Template::Magic 2347 lookups => \%my_restricted_hash ; 2348 2349With this code the lookup is restricted to just the identifiers used in the template, thus the subroutine C<my_potentially_dangerous_sub> is unavailable to the outside world. 2350 2351=back 2352 2353=head2 Embed perl into a template 2354 2355This example represents the maximum degree of inclusion of perl code into a template: in this situation, virtually any code inside the '_EVAL_' block will be executed from the template. 2356 2357B<WARNING>: For obvious reasons you should use this handler ONLY if you are the programmer AND the designer. 2358 2359=over 2360 2361=item the template 2362 2363 {_EVAL_}$char x ($num+1){/_EVAL_} 2364 2365The content of '_EVAL_' block could be any perl expression 2366 2367=item the code 2368 2369 $tm = new Template::Magic 2370 zone_handlers => '_EVAL_' ; 2371 $char = 'W'; 2372 $num = 5; 2373 2374 2375=item the output 2376 2377The handler will generate as the output the evaluated content of the block. 2378 2379 WWWWWW 2380 2381Since a block can contain any quantity of text, you could use this type of configuration as a cheap way to embed perl into (HTML) files. 2382 2383Notice that the default syntax markers ({/}) could somehow clash with perl blocks, so if you want to embed perl into your templates, you should consider to redefine the syntax with some more appropriate marker (See L<"Redefine Markers">). 2384 2385=back 2386 2387=head2 Caching or not the template 2388 2389Template::Magic cache the template structure by default if it is passed as a path to a file. You can avoid the caching either by passing a filehandler or a reference to a template content (not so memory efficient) or by using the 'cache/nocache' L<"options">: 2390 2391 $tm = new Template::Magic 2392 options => 'no_cache' ; 2393 2394=head1 EFFICIENCY 2395 2396The system is very flexible, so you can use it in a variety of ways, but you have to know what is the best option for your needs. 2397 2398=head2 Memory optimization 2399 2400You can avoid waste of memory by avoiding the method L<output()|"output ( template [, temporary lookups ] )"> that needs to collect and store the output in memory. Use L<print()|"print ( template[, temporary lookups ] )"> instead that prints the output while it is produced, without charging the memory. 2401 2402Don't pass big templates contents as a reference, because Template::Magic copies the content in an internal and optimized representation of the template, so you would need twice the memory. 2403 2404Don't do this: 2405 2406 open TEMPLATE, '/path/to/big_template' ; 2407 $big_template = do{local $/; <TEMPLATE>} ; 2408 $output = $tm->output(\$big_template); 2409 print $$output; 2410 2411You can save a lot of typing and a lot of memory if you do this instead: 2412 2413 $tm->print('/path/to/big_template') ; 2414 2415If you need to use C<Template::Magic> with C<CGI::Application> (that requires the run modes method to collect the whole output) you may use L<CGI::Application::Magic|CGI::Application::Magic> or L<Apache::Application::Magic|Apache::Application::Magic> that transparently integrates the template system with the application and avoid the C<output()> method. 2416 2417For memory optimization see also: 2418 2419=over 2420 2421=item * 2422 2423L<"Include and process a template file"> 2424 2425=item * 2426 2427L<"Include (huge) text files without memory charges"> 2428 2429=item * 2430 2431L<"Process (huge) loops iteration by iteration"> 2432 2433=back 2434 2435 2436=head2 Cache 2437 2438If you pass the template as a path, Template::Magic will cache it (in the global C<%Template::Magic::CACHE> hash) and will open and parse it just the first time or if it has been modified, so you can save a lot of processing too! This is a big advantage under mod_perl, where the persistent environment can speed up the process, completely avoiding to read and parse the template file. 2439 2440If for any reason you don't want the template to be cached, you can use the 'no_cache' L<"options">. 2441 2442See also: 2443 2444=over 2445 2446=item * L<"Caching or not the template"> 2447 2448=item * L<load() method|"load( template )"> 2449 2450=item * L<purge_cache() method|"purge_cache ( [template_path] )"> 2451 2452=back 2453 2454=head2 The -compile pragma 2455 2456It has no effect since version 1.39. 2457 2458=head1 SYNTAX GLOSSARY 2459 2460=over 2461 2462=item attributes string 2463 2464The I<attributes string> contains every character between the end of the label I<identifier> and the I<end label> marker. This is optionally used to pass special parameters to a sub. 2465 2466=item block 2467 2468A I<block> is a I<template zone> delimited by (and including) a I<label> and an I<end label>: 2469 2470 +-------+-------------------+------------+ 2471 | LABEL | CONTENT | END_LABEL | 2472 +-------+-------------------+------------+ 2473 2474Example: B<{my_identifier} content of the block {/my_identifier}> 2475 2476where C<'{my_identifier}'> is the LABEL, C<' content of the block '> is the CONTENT and C<'{/my_identifier}'> is the END_LABEL. 2477 2478=item end label 2479 2480An I<end label> is a string in the form of: 2481 2482 +--------------+---------------+------------+------------+ 2483 | START_MARKER | END_MARKER_ID | IDENTIFIER | END_MARKER | 2484 +--------------+---------------+------------+------------+ 2485 2486Example of end label : B<{/my_identifier}> 2487 2488where C<'{'> is the START_MARKER, C<'/'> is the END_MARKER_ID, C<'my_identifier'> is the IDENTIFIER, and C<'}'> is the END_MARKER. 2489 2490=item identifier 2491 2492A I<label identifier> is an alphanumeric name C<(\w+)> that represents (and usually matches) a variable or a subroutine identifier of your code. 2493 2494=item illegal blocks 2495 2496Each block in the template can contain arbitrary quantities of nested labels and/or blocks, but it cannot contain itself (a block with its same identifier), or cannot be cross-nested. 2497 2498B<Legal block>: {block1}...{block2}...{/block2}...{/block1} 2499 2500B<Illegal auto-nested block>: {block1}...{block1}...{/block1}...{/block1} 2501 2502B<Illegal cross-nested block>: {block1}...{block2}...{/block1}...{/block2} 2503 2504If the template contains any illegal block, unpredictable behaviours may occur. 2505 2506=item include label 2507 2508An I<include label> is a I<label> used to include a I<template> file. The I<identifier> must be 'INCLUDE_TEMPLATE' and the attributes string should be a valid path. 2509 2510Example: B<{INCLUDE_TEMPLATE /templates/temp_file.html}> 2511 2512=item label 2513 2514A I<label> is a string in the form of: 2515 2516 +--------------+------------+------------+------------+ 2517 | START_MARKER | IDENTIFIER | ATTRIBUTES | END_MARKER | 2518 +--------------+------------+------------+------------+ 2519 2520Example: B<{my_identifier attribute1 attribute2}> 2521 2522where C<'{'> is the START_MARKER, C<'my_identifier'> is the IDENTIFIER, C<'attribute1 attribute2'> are the ATTRIBUTES and C<'}'> is the END_MARKER. 2523 2524=item lookup 2525 2526The action to match label I<identifier> with code identifier (variable, subroutine and method identifier and hash keys). 2527 2528=item main template zone 2529 2530The 'root' zone representing the whole template content 2531 2532=item markers 2533 2534The markers that defines labels and blocks. These are the default values of the markers that define the label: 2535 2536 START_MARKER: { 2537 END_MARKER_ID: / 2538 END_MARKER: } 2539 2540You can redefine them by using the C<markers> constructor array. (see L<"Redefine Markers"> and L<markers>). 2541 2542=item matching identifier 2543 2544The identifier (symbol name or key name) in the code that is matching with the zone or label identifier 2545 2546=item merger process 2547 2548The process that merges runtime values with a I<template> producing the final output 2549 2550=item nested block 2551 2552A I<nested block> is a I<block> contained in another I<block>: 2553 2554 +----------------------+ 2555 | CONTAINER_BLOCK | 2556 | +----------------+ | 2557 | | NESTED_BLOCK | | 2558 | +----------------+ | 2559 +----------------------+ 2560 2561Example: 2562 {my_container_identifier} 2563 B<{my_nested_identifier} content of the block {/my_nested_identifier}> 2564 {/my_container_identifier} 2565 2566where all the above is the CONTAINER_BLOCK and C<'{my_nested_identifier} content of the block {/my_nested_identifier}'> is the NESTED_BLOCK. 2567 2568=item output 2569 2570The I<output> is the result of the merger of runtimes values with a template 2571 2572=item template 2573 2574A I<template> is a text content or a text file (i.e. plain, HTML, XML, etc.) containing some I<label> or I<block>. 2575 2576=item value type 2577 2578The type of the value found by a lookup (i.e. UNDEF, SCALAR, HASH, ARRAY, ...), that is usually used in the I<value handler> condition to trigger the I<value handler>. 2579 2580=item zone 2581 2582A I<zone> is an area in the template that must have an I<identifier>, may have an I<attributes string> and may have a I<content>. A zone without any content is also called I<label>, while a zone with content is also called I<block>. 2583 2584=item zone object 2585 2586A I<zone object> is an internal object representing a zone. 2587 2588=back 2589 2590=head1 SEE ALSO 2591 2592=over 2593 2594=item * L<Template::Magic::Zone|Template::Magic::Zone> 2595 2596=item * L<Template::Magic::HTML|Template::Magic::HTML> 2597 2598=item * L<Template::Magic::Pager|Template::Magic::Pager> 2599 2600=item * L<CGI::Builder::Magic|CGI::Builder::Magic> 2601 2602=item * L<CGI::Application::Magic|CGI::Application::Magic> 2603 2604=item * L<Apache::Application::Magic|Apache::Application::Magic> 2605 2606=back 2607 2608=head1 SUPPORT 2609 2610Support for all the modules of the Template Magic System is via the mailing list. The list is used for general support on the use of the Template::Magic, announcements, bug reports, patches, suggestions for improvements or new features. The API to the Magic Template System is stable, but if you use it in a production environment, it's probably a good idea to keep a watch on the list. 2611 2612You can join the Template Magic System mailing list at this url: 2613 2614L<http://lists.sourceforge.net/lists/listinfo/template-magic-users> 2615 2616=head1 AUTHOR and COPYRIGHT 2617 2618� 2004-2005 by Domizio Demichelis (L<http://perl.4pro.net>) 2619 2620All Rights Reserved. This module is free software. It may be used, redistributed and/or modified under the same terms as perl itself. 2621 2622=head1 CREDITS 2623 2624Thanks to I<Mark Overmeer> L<http://search.cpan.org/author/MARKOV/> which has submitted a variety of code cleanups/speedups and other useful suggestions. 2625 2626A special thanks to Megyaszai Sandor for his very detailed revision of the POD. 2627 2628=cut