Cees Hek wrote:

You should look at using Regexp::Common, specifically the
Regexp::Common::balanced module.  The following should do the trick:

$RE{balanced}{-begin => "[%"}{-end => "%]"}{-keep}
Thank you for the tip. It seems like this code actually will move inner tags out into variables and do it properly. This code will only allow one level of nesting, but with some tweaking I guess it could be made to work recursively. Figured I should be nice to post the code in case anyone else has similar problems.

Thanks a lot for helping out!

-- Robin

#!/usr/bin/perl

use strict;
use Regexp::Common;

# Content with nested TT tags
my $text=$ARGV[0] || <<'EOM';
[% popup('begin',"[% embed('2345-2345-2345', { type => 'image', mimetype => 'image/gif' } ) %] Hva har du lært? [% link('xyz') %]", { event => 'onclick', title => 'Test' } ) %]
noe er morsomt[% popup('end') %]
[% uri('1234-1234-1234') %]
[% link('1234-1234-1234', { title => 'bla bla' } ) %]
EOM

$text=~s/$RE{balanced}{-begin => "[%"}{-end => "%]"}{-keep}/ match_tt_outer($1) /ge;
print $text;
exit;

# Match all outer tags in the text
sub match_tt_outer {
   my $str=shift @_;

   my $counter=1; my $vars=[];
   $str=~s/^\[\%//; $str=~s/\%\]$//; # remove start/close tag

   # If string contains nested tags, run them through match_tt_inner which
   # returns output variable, and store the actual code in an array
if ( $RE{balanced}{-begin => "[%"}{-end => "%]"}{-keep}->matches($str) ) { $str=~s/$RE{balanced}{-begin => "[%"}{-end => "%]"}{-keep}/ match_tt_inner($1,\$counter, $vars) /ge;

       # Create and return variable list + outer TT function
       my $return_data="[%\n";
       for(my $index=1; $index < @{ $vars }; $index++) {
           $return_data.=" out$index=" . $vars->[$index] . ";\n";
       }
       $return_data.="$str\n%]";
       return $return_data;
   }
   else {
       return "[%$str%]"; # Return asis if no nesting
   }
}

sub match_tt_inner {
   my $str=shift @_;
   my $counter_ref=shift @_;
   my $vars=shift @_;

   $str=~s/^\[\%\s//; $str=~s/\s\%\]$//; # remove start/close tag

   # FIXME: I guess here is the place to do something smart with calling
   # match_tt_inner() again if you want this to work recursively.
   $vars->[${$counter_ref}]=$str;
   my $varname='$out' . ${$counter_ref};

   ${$counter_ref}++;
   return $varname;
}



_______________________________________________
templates mailing list
[email protected]
http://lists.template-toolkit.org/mailman/listinfo/templates

Reply via email to