Ovid has asked for the wisdom of the Perl Monks concerning the following question:

A few days ago, I was asking about how to make Template Toolkit automatically insert identifying start and end comments around each INCLUDEd template. Here's what I finally came up with.

BEGIN { use Template::Context; no strict; no warnings; my $sub = *{$Template::Context::{include}}{CODE}; *Template::Context::include = sub { _wrapper( $sub, @_ ); }; $sub = *{$Template::Context::{process}}{CODE}; *Template::Context::process = sub { _wrapper( $sub, @_ ); }; } sub _wrapper { my $sub = shift; my $tmpl; if ( ! ref $_[1] ) { # [% INCLUDE ... %] $tmpl = $_[1]; } else { # $template->process(...) $tmpl = $_[1]->{name}; } my $data = $sub->(@_); $data = "<!-- START: $tmpl -->\n$data\n<!-- END: $tmpl -->"; return $data; }

Note that this is in an entirely separate module and leaves Template::Context.pm intact.

I need to add HTML::Entities to handle problems with funny characters in the template names and probably should strip the &process override and use use the PRE_PROCESS and POST_PROCESS directives. However, rather than go much further, I am wondering if anyone familiar with TT sees any pitfalls here? I'm reading through the code and docs and don't see anything wrong, but the code is very complex and I know I could easily have missed something.

Cheers,
Ovid

Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Replies are listed 'Best First'.
Re: Overriding Template Toolkit Internals
by jehuni (Pilgrim) on Apr 10, 2002 at 16:35 UTC

      Actually, a reponse to one of my messages to that list lead to the following code:

      package Onsite::Template::Context; use strict; use base qw/ Template::Context /; sub include { my $self = shift; my $template = $_[0]; join "\n", "<!-- START: $template -->", $self->SUPER::include(@_), "<!-- END: $template -->"; } 1;

      Then, in the code that actually uses Template Toolkit:

      use Template; use Template::Config; $Template::Config::CONTEXT = 'Onsite::Template::Context';

      That solved the problem nicely without my rude hack. Basically, the Config module has globals that control all of the modules that it uses. When a Template object is instantiated, &Template::Config::load is called which then will require all modules, allowing them to be overridden at run time. It's a neat solution.

      The only thing about it that bugs me is that I kept reading and reading through the online Template Toolkit documentation and didn't see that anywhere. I'm sure it's there, I just can't find it.

      Cheers,
      Ovid

      Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.