templates

gav on 2002-08-13T16:09:05

I wanted a nice way of being able to pull TT2 or HTML::Template templates from a database and handle them in some kind of unified way. This is my first attempt and seems rather hackish :)

Is there a nicer way to do this?

package My::Burner;

sub new {
    my (undef, $type, $data) = @_;
    my $class = "My::Burner::$type";
    return $class->new($data);
}

package My::Burner::Template;

use Template;

sub new {
    my ($class, $data) = @_;
    my $self = { handler => Template->new, tmpl => $data };
    bless $self, $class;
}

sub param {
    my ($self, $param, $value) = @_;
    $self->{params}->{$param} = $value;
}

sub process {
    my $self = shift;
    $self->{handler}->process($self->{tmpl}, $self->{params});
}

package My::Burner::HTML::Template;

use HTML::Template;

sub new {
    my ($class, $data) = @_;
    my $self = { handler => HTML::Template->new(scalarref => $data) };
    bless $self, $class;
}

sub param {
    my $self = shift;
    $self->{handler}->param(@_);
}

sub process {
    my $self = shift;
    print $self->{handler}->output;
}


Just did that

ajtaylor on 2002-08-13T16:57:34

Funny you should ask as I just did something similar yesterday. Except I didn't have a unified "process" method like you do. I also lazy load the appropriate module at runtime so I don't pull in the large Template package if I'm using HTML::Template.

But I really like your idea of a "Burner" object. This reminds me of the approach used in Bricolagem which gives you flexibility in what template system you use. I think I'm going to redo things to implement this methodology. It's a little tricky as you saw because H:T & TT use different paradigms for setting up the template & loading template data. But it's not insurmountable. Thanks for the idea!

Re:Just did that

gav on 2002-08-13T17:07:45

I stole the name and idea from Bricolage :)

Loading the modules isn't an issue to me as I use PerlModule with mod_perl to preload those modules anyway. I've also been thinking about how things work and I've changed it to reuse the same TT2 object each time.

I'll post more when I have fleshed things out even more, perhaps Template::Burner may be CPAN worthy someday...