Re: Can a template tell if it has been PROCESSed or INCLUDEd?

Andy Wardley <[email protected]> Thu, 25 Sep 2014 19:09:21 +0100
Newsgroups gmane.comp.lang.perl.modules.template-toolkit
Message-ID <[email protected]>
On 25/09/2014 18:35, Andy Lester wrote:
> The point of the check is for a template that knows that it must be
> invoked via INCLUDE to complain if it's been invoked with PROCESS.

Something else that came to mind while I was out walking the dog...

If you don't mind subclassing Template::Context then you could put your 
own wrapper methods around include() and process() to set a stash variable.

   package Your::Template::Context;
   use base 'Template::Context';

   sub include {
       my ($self, $template, $params) = @_;
       $self->stash->set( tt_call => 'INCLUDE' );
       # don't be tempted to call $self->SUPER::include()
       # because that's a wrapper around process()
       return $self->SUPER::process($template, $params, 1);
   }

   sub process {
       my $self = shift;
       $self->stash->set( tt_call => 'PROCESS' );
       return $self->SUPER::process(@_);
   }

Engage it like so:

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

Then [% tt_call %] will be set to 'INCLUDE' or 'PROCESS' depending on 
how the template was called.

Note that the WRAPPER directive calls the include() method (and thus is 
"safe" for your purposes) so tt_call will be set to 'INCLUDE' in that case.

Cheers
Andy