[reposted - not CC'd to the list first time around]

Denis Banovic wrote:
> Yes, that's correct, I'm looking for a way to convert (some parts of ) 
> TT ( eg. [ FOREACH and IF ] ) to PHP. Our PHP templates are very similar 
> to TT-Templates, 

One approach is to subclass Template::Directive (the part of TT that
generates compiled Perl code from the source template) and intercept
the various methods that generate the foreach, if, and other directives.

In the usual case, the methods generate Perl code to implements the foreach, 
if, etc.  e.g. 

  # template            # regular compiled Perl code
  [% IF x %]...    =>   if ($stash->get('x')) { ...

You would instead need to generate Perl code that when run, emits the PHP 
equivalent of the original directive.

  # template            # output PHP directive
  [% IF x %]...    =>   $output .= '<? if ($x) { ?>...';

The end result is that you process your TT templates, and you get PHP
templates generated as the output.

There is a Template::Directive::PHP module attached which I just knocked
up to test this idea.  Be warned that it is a proof of concept only and
will almost certainly break when you feed it other TT directives.  However
it may be useful as a starting point if you decide that's a good way to go.

The difficulty is that in TT2 there isn't a clear separation between the
parser and back end directive generator (yet another weakness that I've 
been trying to address in TT3).  You need to become intimately familiar 
with the workings and output generated by both the parser and current 
Template::Directives methods, and it's not something to be taken lightly.  
I suspect there may be several things that are hard, if not impossible to 
do correctly without hacking on the parser grammar itself, and therein 
lies dragons!  

So if you're not already totally confused by the examples above, you soon
will be once you start delving deeper  :-)

Anyway, here's an example of my quick hack in use:

  use strict;
  use warnings;
  use Template;
  use Template::Parser;
  use Template::Directive::PHP;

  # -d flag enables debugging output
  if (grep(/^-d/, @ARGV)) {
      $Template::Parser::DEBUG = 1;
      $Template::Directive::PRETTY = 1;
  }

  my $tt = Template->new( FACTORY => 'Template::Directive::PHP' )
      || die Template->error();

  $tt->process(\*DATA) 
      || die $tt->error();

  __DATA__
  This is a test template
  [% IF x < 10 %]
     do this
  [% ELSIF y < 20 %]
     do this instead
  [% ELSE %]
     don't do anything at all
  [% END %]
  
  [% z %]

  [% FOREACH y IN z %]
     y is [% y %]
  [% END %]

And this is the output:

  This is a test template
  <? if ($x < 10) { ?>
     do this
  <? } elsif ($y < 20) { ?>
     do this instead
  <? } else { ?>
     don't do anything at all
  <? } ?>
  
  <? $z ?>
  
  <? foreach ($z as $y) { ?>
     y is <? $y ?>
  <? } ?>


Cheers
A

Attachment: PHP.pm
Description: Perl program

Reply via email to