On Fri, 6 Jun 2003, Tom Insam wrote:

> Ok, so I'd like to do something like
> 
> 
> #!/usr/bin/perl
> my $thing = Stuff->new();
> $tt->process("template.tem", $thing);
> 
> package Stuff;
> 
> sub new {
>      return bless {}, shift;
> }
> 
> sub colour {
>      my ($self) = @_;
>      return "orange!";
> }
> 
> 
> And in the template:
> 
> <html>
> <body>
> [% colour %]
> </body>
> </html>
> 
> ie, I'd like to pass a blessed hash to process() and call it's object 
> methods as I would keys/values in it. I can already do this if I pass 
> it as a member:
> 
> $tt->process("template.tem", { object=>$thing });
> then [% object.colour %]
> 
> but I can't pass an object as the top-level thing.
> 
> I talked to Mark about this yesterday, and he suggested you could 
> fake it by making a shallow copy of the hash you were going to pass, 
> and then sticking anonymous subs into the copy pointing at the 
> package methods. This feels evil but possible, but I lack the perl-fu 
> to get a list of package methods..

Could you have a method in your object that returns a list of key/value 
pairs, then use this to populate the template hash ?

No doubt there is some magic that you can use to find all the methods 
automatically but since you're writing the class you can add them 
yourself.

Something like (wildly untested :) :

package Stuff;

sub config_list {
  my $self = shift;
  my @methods = qw/ colour /;
  
  return map { $_, $self->$_ } @methods;
}

Then in your perl code:

  
  #!/usr/bin/perl
  my $thing = Stuff->new();
  $tt->process("template.tem", { $thing->config_list } );

Dunno, it might work :)

Simon.

-- 
"Is there any tea on this spaceship ?"
 


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

Reply via email to