home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2004 December / PCpro_2004_12.ISO / files / webserver / tsw / TSW_3.4.0.exe / Apache2 / perl / Document.pm < prev    next >
Encoding:
Perl POD Document  |  2004-01-30  |  14.8 KB  |  493 lines

  1. ##============================================================= -*-Perl-*-
  2. #
  3. # Template::Document
  4. #
  5. # DESCRIPTION
  6. #   Module defining a class of objects which encapsulate compiled
  7. #   templates, storing additional block definitions and metadata 
  8. #   as well as the compiled Perl sub-routine representing the main
  9. #   template content.
  10. #
  11. # AUTHOR
  12. #   Andy Wardley   <abw@kfs.org>
  13. #
  14. # COPYRIGHT
  15. #   Copyright (C) 1996-2000 Andy Wardley.  All Rights Reserved.
  16. #   Copyright (C) 1998-2000 Canon Research Centre Europe Ltd.
  17. #
  18. #   This module is free software; you can redistribute it and/or
  19. #   modify it under the same terms as Perl itself.
  20. #----------------------------------------------------------------------------
  21. #
  22. # $Id: Document.pm,v 2.71 2004/01/13 16:19:10 abw Exp $
  23. #
  24. #============================================================================
  25.  
  26. package Template::Document;
  27.  
  28. require 5.004;
  29.  
  30. use strict;
  31. use vars qw( $VERSION $ERROR $COMPERR $DEBUG $AUTOLOAD );
  32. use base qw( Template::Base );
  33. use Template::Constants;
  34.  
  35. $VERSION = sprintf("%d.%02d", q$Revision: 2.71 $ =~ /(\d+)\.(\d+)/);
  36.  
  37.  
  38. #========================================================================
  39. #                     -----  PUBLIC METHODS -----
  40. #========================================================================
  41.  
  42. #------------------------------------------------------------------------
  43. # new(\%document)
  44. #
  45. # Creates a new self-contained Template::Document object which 
  46. # encapsulates a compiled Perl sub-routine, $block, any additional 
  47. # BLOCKs defined within the document ($defblocks, also Perl sub-routines)
  48. # and additional $metadata about the document.
  49. #------------------------------------------------------------------------
  50.  
  51. sub new {
  52.     my ($class, $doc) = @_;
  53.     my ($block, $defblocks, $metadata) = @$doc{ qw( BLOCK DEFBLOCKS METADATA ) };
  54.     $defblocks ||= { };
  55.     $metadata  ||= { };
  56.  
  57.     # evaluate Perl code in $block to create sub-routine reference if necessary
  58.     unless (ref $block) {
  59.         local $SIG{__WARN__} = \&catch_warnings;
  60.         $COMPERR = '';
  61.  
  62.         # DON'T LOOK NOW! - blindly untainting can make you go blind!
  63.         $block =~ /(.*)/s;
  64.         $block = $1;
  65.         
  66.         $block = eval $block;
  67.         return $class->error($@)
  68.             unless defined $block;
  69.     }
  70.  
  71.     # same for any additional BLOCK definitions
  72.     @$defblocks{ keys %$defblocks } = 
  73.         # MORE BLIND UNTAINTING - turn away if you're squeamish
  74.         map { 
  75.             ref($_) 
  76.                 ? $_ 
  77.                 : ( /(.*)/s && eval($1) or return $class->error($@) )
  78.             } values %$defblocks;
  79.     
  80.     bless {
  81.         %$metadata,
  82.         _BLOCK     => $block,
  83.         _DEFBLOCKS => $defblocks,
  84.         _HOT       => 0,
  85.     }, $class;
  86. }
  87.  
  88.  
  89. #------------------------------------------------------------------------
  90. # block()
  91. #
  92. # Returns a reference to the internal sub-routine reference, _BLOCK, 
  93. # that constitutes the main document template.
  94. #------------------------------------------------------------------------
  95.  
  96. sub block {
  97.     return $_[0]->{ _BLOCK };
  98. }
  99.  
  100.  
  101. #------------------------------------------------------------------------
  102. # blocks()
  103. #
  104. # Returns a reference to a hash array containing any BLOCK definitions 
  105. # from the template.  The hash keys are the BLOCK nameand the values
  106. # are references to Template::Document objects.  Returns 0 (# an empty hash)
  107. # if no blocks are defined.
  108. #------------------------------------------------------------------------
  109.  
  110. sub blocks {
  111.     return $_[0]->{ _DEFBLOCKS };
  112. }
  113.  
  114.  
  115. #------------------------------------------------------------------------
  116. # process($context)
  117. #
  118. # Process the document in a particular context.  Checks for recursion,
  119. # registers the document with the context via visit(), processes itself,
  120. # and then unwinds with a large gin and tonic.
  121. #------------------------------------------------------------------------
  122.  
  123. sub process {
  124.     my ($self, $context) = @_;
  125.     my $defblocks = $self->{ _DEFBLOCKS };
  126.     my $output;
  127.  
  128.  
  129.     # check we're not already visiting this template
  130.     return $context->throw(Template::Constants::ERROR_FILE, 
  131.                            "recursion into '$self->{ name }'")
  132.         if $self->{ _HOT } && ! $context->{ RECURSION };   ## RETURN ##
  133.  
  134.     $context->visit($self, $defblocks);
  135.  
  136.     $self->{ _HOT } = 1;
  137.     eval {
  138.         my $block = $self->{ _BLOCK };
  139.         $output = &$block($context);
  140.     };
  141.     $self->{ _HOT } = 0;
  142.  
  143.     $context->leave();
  144.  
  145.     die $context->catch($@)
  146.         if $@;
  147.     
  148.     return $output;
  149. }
  150.  
  151.  
  152. #------------------------------------------------------------------------
  153. # AUTOLOAD
  154. #
  155. # Provides pseudo-methods for read-only access to various internal 
  156. # members. 
  157. #------------------------------------------------------------------------
  158.  
  159. sub AUTOLOAD {
  160.     my $self   = shift;
  161.     my $method = $AUTOLOAD;
  162.  
  163.     $method =~ s/.*:://;
  164.     return if $method eq 'DESTROY';
  165. #    my ($pkg, $file, $line) = caller();
  166. #    print STDERR "called $self->AUTOLOAD($method) from $file line $line\n";
  167.     return $self->{ $method };
  168. }
  169.  
  170.  
  171. #========================================================================
  172. #                     -----  PRIVATE METHODS -----
  173. #========================================================================
  174.  
  175.  
  176. #------------------------------------------------------------------------
  177. # _dump()
  178. #
  179. # Debug method which returns a string representing the internal state
  180. # of the object.
  181. #------------------------------------------------------------------------
  182.  
  183. sub _dump {
  184.     my $self = shift;
  185.     my $dblks;
  186.     my $output = "$self : $self->{ name }\n";
  187.  
  188.     $output .= "BLOCK: $self->{ _BLOCK }\nDEFBLOCKS:\n";
  189.  
  190.     if ($dblks = $self->{ _DEFBLOCKS }) {
  191.     foreach my $b (keys %$dblks) {
  192.         $output .= "    $b: $dblks->{ $b }\n";
  193.     }
  194.     }
  195.  
  196.     return $output;
  197. }
  198.  
  199.  
  200. #========================================================================
  201. #                      ----- CLASS METHODS -----
  202. #========================================================================
  203.  
  204. #------------------------------------------------------------------------
  205. # as_perl($content)
  206. #
  207. # This method expects a reference to a hash passed as the first argument
  208. # containing 3 items:
  209. #     METADATA   # a hash of template metadata
  210. #     BLOCK      # string containing Perl sub definition for main block
  211. #     DEFBLOCKS  # hash containing further subs for addional BLOCK defs
  212. # It returns a string containing Perl code which, when evaluated and 
  213. # executed, will instantiate a new Template::Document object with the 
  214. # above data.  On error, it returns undef with an appropriate error
  215. # message set in $ERROR.
  216. #------------------------------------------------------------------------
  217.  
  218. sub as_perl {
  219.     my ($class, $content) = @_;
  220.     my ($block, $defblocks, $metadata) = @$content{ qw( BLOCK DEFBLOCKS METADATA ) };
  221.  
  222.     $block =~ s/\n/\n    /g;
  223.     $block =~ s/\s+$//;
  224.  
  225.     $defblocks = join('', map {
  226.     my $code = $defblocks->{ $_ };
  227.     $code =~ s/\n/\n        /g;
  228.     $code =~ s/\s*$//;
  229.     "        '$_' => $code,\n";
  230.     } keys %$defblocks);
  231.     $defblocks =~ s/\s+$//;
  232.  
  233.     $metadata = join('', map { 
  234.     my $x = $metadata->{ $_ }; 
  235.     $x =~ s/(['\\])/\\$1/g; 
  236.     "        '$_' => '$x',\n";
  237.     } keys %$metadata);
  238.     $metadata =~ s/\s+$//;
  239.  
  240.     return <<EOF
  241. #------------------------------------------------------------------------
  242. # Compiled template generated by the Template Toolkit version $Template::VERSION
  243. #------------------------------------------------------------------------
  244.  
  245. $class->new({
  246.     METADATA => {
  247. $metadata
  248.     },
  249.     BLOCK => $block,
  250.     DEFBLOCKS => {
  251. $defblocks
  252.     },
  253. });
  254. EOF
  255. }
  256.  
  257.  
  258. #------------------------------------------------------------------------
  259. # write_perl_file($filename, \%content)
  260. #
  261. # This method calls as_perl() to generate the Perl code to represent a
  262. # compiled template with the content passed as the second argument.
  263. # It then writes this to the file denoted by the first argument.
  264. #
  265. # Returns 1 on success.  On error, sets the $ERROR package variable
  266. # to contain an error message and returns undef.
  267. #------------------------------------------------------------------------
  268.  
  269. sub write_perl_file {
  270.     my ($class, $file, $content) = @_;
  271.     my ($fh, $tmpfile);
  272.     
  273.     return $class->error("invalid filename: $file")
  274.     unless $file =~ /^(.+)$/s;
  275.  
  276.     eval {
  277.         require File::Temp;
  278.         require File::Basename;
  279.         ($fh, $tmpfile) = File::Temp::tempfile( 
  280.             DIR => File::Basename::dirname($file) 
  281.         );
  282.     print $fh $class->as_perl($content) || die $!;
  283.     close($fh);
  284.     };
  285.     return $class->error($@) if $@;
  286.     return rename($tmpfile, $file)
  287.     || $class->error($!);
  288. }
  289.  
  290.  
  291. #------------------------------------------------------------------------
  292. # catch_warnings($msg)
  293. #
  294. # Installed as
  295. #------------------------------------------------------------------------
  296.  
  297. sub catch_warnings {
  298.     $COMPERR .= join('', @_); 
  299. }
  300.  
  301.     
  302. 1;
  303.  
  304. __END__
  305.  
  306.  
  307. #------------------------------------------------------------------------
  308. # IMPORTANT NOTE
  309. #   This documentation is generated automatically from source
  310. #   templates.  Any changes you make here may be lost.
  311. #   The 'docsrc' documentation source bundle is available for download
  312. #   from http://www.template-toolkit.org/docs.html and contains all
  313. #   the source templates, XML files, scripts, etc., from which the
  314. #   documentation for the Template Toolkit is built.
  315. #------------------------------------------------------------------------
  316.  
  317. =head1 NAME
  318.  
  319. Template::Document - Compiled template document object
  320.  
  321. =head1 SYNOPSIS
  322.  
  323.     use Template::Document;
  324.  
  325.     $doc = Template::Document->new({
  326.     BLOCK => sub { # some perl code; return $some_text },
  327.     DEFBLOCKS => {
  328.         header => sub { # more perl code; return $some_text },
  329.         footer => sub { # blah blah blah; return $some_text },
  330.     },
  331.     METADATA => {
  332.         author  => 'Andy Wardley',
  333.         version => 3.14,
  334.     }
  335.     }) || die $Template::Document::ERROR;
  336.  
  337.     print $doc->process($context);
  338.  
  339. =head1 DESCRIPTION
  340.  
  341. This module defines an object class whose instances represent compiled
  342. template documents.  The Template::Parser module creates a
  343. Template::Document instance to encapsulate a template as it is compiled
  344. into Perl code.
  345.  
  346. The constructor method, new(), expects a reference to a hash array
  347. containing the BLOCK, DEFBLOCKS and METADATA items.  The BLOCK item
  348. should contain a reference to a Perl subroutine or a textual
  349. representation of Perl code, as generated by the Template::Parser
  350. module, which is then evaluated into a subroutine reference using
  351. eval().  The DEFLOCKS item should reference a hash array containing
  352. further named BLOCKs which may be defined in the template.  The keys
  353. represent BLOCK names and the values should be subroutine references
  354. or text strings of Perl code as per the main BLOCK item.  The METADATA
  355. item should reference a hash array of metadata items relevant to the
  356. document.
  357.  
  358. The process() method can then be called on the instantiated
  359. Template::Document object, passing a reference to a Template::Content
  360. object as the first parameter.  This will install any locally defined
  361. blocks (DEFBLOCKS) in the the contexts() BLOCKS cache (via a call to
  362. visit()) so that they may be subsequently resolved by the context.  The 
  363. main BLOCK subroutine is then executed, passing the context reference
  364. on as a parameter.  The text returned from the template subroutine is
  365. then returned by the process() method, after calling the context leave()
  366. method to permit cleanup and de-registration of named BLOCKS previously
  367. installed.
  368.  
  369. An AUTOLOAD method provides access to the METADATA items for the document.
  370. The Template::Service module installs a reference to the main 
  371. Template::Document object in the stash as the 'template' variable.
  372. This allows metadata items to be accessed from within templates, 
  373. including PRE_PROCESS templates.
  374.  
  375. header:
  376.  
  377.     <html>
  378.     <head>
  379.     <title>[% template.title %]
  380.     </head>
  381.     ...
  382.  
  383. Template::Document objects are usually created by the Template::Parser
  384. but can be manually instantiated or sub-classed to provide custom
  385. template components.
  386.  
  387. =head1 METHODS
  388.  
  389. =head2 new(\%config)
  390.  
  391. Constructor method which accept a reference to a hash array containing the
  392. structure as shown in this example:
  393.  
  394.     $doc = Template::Document->new({
  395.     BLOCK => sub { # some perl code; return $some_text },
  396.     DEFBLOCKS => {
  397.         header => sub { # more perl code; return $some_text },
  398.         footer => sub { # blah blah blah; return $some_text },
  399.     },
  400.     METADATA => {
  401.         author  => 'Andy Wardley',
  402.         version => 3.14,
  403.     }
  404.     }) || die $Template::Document::ERROR;
  405.  
  406. BLOCK and DEFBLOCKS items may be expressed as references to Perl subroutines
  407. or as text strings containing Perl subroutine definitions, as is generated
  408. by the Template::Parser module.  These are evaluated into subroutine references
  409. using eval().
  410.  
  411. Returns a new Template::Document object or undef on error.  The error() class
  412. method can be called, or the $ERROR package variable inspected to retrieve
  413. the relevant error message.
  414.  
  415. =head2 process($context)
  416.  
  417. Main processing routine for the compiled template document.  A reference to 
  418. a Template::Context object should be passed as the first parameter.  The 
  419. method installs any locally defined blocks via a call to the context 
  420. visit() method, processes it's own template, passing the context reference
  421. by parameter and then calls leave() in the context to allow cleanup.
  422.  
  423.     print $doc->process($context);
  424.  
  425. Returns a text string representing the generated output for the template.
  426. Errors are thrown via die().
  427.  
  428. =head2 block()
  429.  
  430. Returns a reference to the main BLOCK subroutine.
  431.  
  432. =head2 blocks()
  433.  
  434. Returns a reference to the hash array of named DEFBLOCKS subroutines.
  435.  
  436. =head2 AUTOLOAD
  437.  
  438. An autoload method returns METADATA items.
  439.  
  440.     print $doc->author();
  441.  
  442. =head1 PACKAGE SUB-ROUTINES
  443.  
  444. =head2 write_perl_file(\%config)
  445.  
  446. This package subroutine is provided to effect persistance of compiled
  447. templates.  If the COMPILE_EXT option (to indicate a file extension
  448. for saving compiled templates) then the Template::Parser module calls
  449. this subroutine before calling the new() constructor.  At this stage,
  450. the parser has a representation of the template as text strings
  451. containing Perl code.  We can write that to a file, enclosed in a
  452. small wrapper which will allow us to susequently require() the file
  453. and have Perl parse and compile it into a Template::Document.  Thus we
  454. have persistance of compiled templates.
  455.  
  456. =head1 AUTHOR
  457.  
  458. Andy Wardley E<lt>abw@andywardley.comE<gt>
  459.  
  460. L<http://www.andywardley.com/|http://www.andywardley.com/>
  461.  
  462.  
  463.  
  464.  
  465. =head1 VERSION
  466.  
  467. 2.71, distributed as part of the
  468. Template Toolkit version 2.13, released on 30 January 2004.
  469.  
  470. =head1 COPYRIGHT
  471.  
  472.   Copyright (C) 1996-2004 Andy Wardley.  All Rights Reserved.
  473.   Copyright (C) 1998-2002 Canon Research Centre Europe Ltd.
  474.  
  475. This module is free software; you can redistribute it and/or
  476. modify it under the same terms as Perl itself.
  477.  
  478. =head1 SEE ALSO
  479.  
  480. L<Template|Template>, L<Template::Parser|Template::Parser>
  481.  
  482. =cut
  483.  
  484. # Local Variables:
  485. # mode: perl
  486. # perl-indent-level: 4
  487. # indent-tabs-mode: nil
  488. # End:
  489. #
  490. # vim: expandtab shiftwidth=4:
  491.