[Templates] TT and dependencies

Andy Wardley abw@andywardley.com
Tue, 14 Oct 2003 10:52:14 +0100


I wrote:
> This could probably be bodged onto TT2.  I'm looking into it.  

The following works if you get the latest version of TT from CVS.


#========================================================================
# Template::Context::Tracker
#
# This is a hacked subclass which modifies the visit() and leave() 
# methods to track which templates depend on which others.
#========================================================================

package Template::Context::Tracker;
use Template::Context;
use base qw( Template::Context );

sub visit {
    my ($self, $document, $blocks) = @_;
    my $dname = $document->{ name };

    unshift(@{ $self->{ BLKSTACK } }, $blocks);

    # DEPEND_VISITING is a stack of templates that we're visiting
    my $vlist = $self->{ DEPEND_VISITING } ||= [ ];

    if (@$vlist) {
        my $current = $vlist->[-1];

        # DEPEND_DEPENDANT is a hash of dependants hashes
        $self->{ DEPEND_DEPENDANT }->{ $current }->{ $dname } = 1;
    }

    push(@$vlist, $dname);
}

sub leave {
    my $self = shift;
    shift(@{ $self->{ BLKSTACK } });
    pop(@{ $self->{ DEPEND_VISITING } });
}

sub dependants {
    my $self = shift;
    return $self->{ DEPEND_DEPENDANT };
}

#========================================================================
# test program
#========================================================================

use Template;

my $context = Template::Context::Tracker->new( INCLUDE_PATH => 'lib' )
    || die Template::Context::Tracker->error();

my $tt = Template->new( CONTEXT => $context )
    || die Template->error();

my $out;
$tt->process('index.html', undef, \$out) || die $tt->error();

my $deps = $tt->context->dependants()
    || die $tt->context->error();

while (my ($key, $val) = each %$deps) {
    print $key, ' : ', join(', ', keys %$val), "\n";
}

#=== output generated for some dummy templates ===

menu : menuitem
headlines : headline
index.html : menu, footer, header
footer : table, copyright
header : table, headlines


Looks good, eh?  Implementing this as a patch for ttree is left as an 
excercise for the reader... :-)


A