| 1 | |||
| 2 | ########################################################################### | ||
| 3 | # Copyright (c) Nate Wiger http://nateware.com. All Rights Reserved. | ||
| 4 | # Please visit http://formbuilder.org for tutorials, support, and examples. | ||
| 5 | ########################################################################### | ||
| 6 | |||
| 7 | package CGI::FormBuilder::Template::TT2; | ||
| 8 | |||
| 9 | =head1 NAME | ||
| 10 | |||
| 11 | CGI::FormBuilder::Template::TT2 - FormBuilder interface to Template Toolkit | ||
| 12 | |||
| 13 | =head1 SYNOPSIS | ||
| 14 | |||
| 15 | my $form = CGI::FormBuilder->new( | ||
| 16 | fields => \@fields, | ||
| 17 | template => { | ||
| 18 | type => 'TT2', | ||
| 19 | template => 'form.tmpl', | ||
| 20 | variable => 'form', | ||
| 21 | } | ||
| 22 | ); | ||
| 23 | |||
| 24 | =cut | ||
| 25 | |||
| 26 | use Carp; | ||
| 27 | use strict; | ||
| 28 | use warnings; | ||
| 29 | no warnings 'uninitialized'; | ||
| 30 | |||
| 31 | use CGI::FormBuilder::Util; | ||
| 32 | use Template; | ||
| 33 | |||
| 34 | |||
| 35 | our $VERSION = '3.10'; | ||
| 36 | |||
| 37 | sub new { | ||
| 38 | my $self = shift; | ||
| 39 | my $class = ref($self) || $self; | ||
| 40 | my $opt = arghash(@_); | ||
| 41 | |||
| 42 | $opt->{engine} = Template->new($opt->{engine} || {}) | ||
| 43 | || puke $Template::ERROR unless UNIVERSAL::isa($opt->{engine}, 'Template'); | ||
| 44 | |||
| 45 | return bless $opt, $class; | ||
| 46 | } | ||
| 47 | |||
| 48 | sub engine { | ||
| 49 | return shift()->{engine}; | ||
| 50 | } | ||
| 51 | |||
| 52 | sub render { | ||
| 53 | my $self = shift; | ||
| 54 | my $tvar = shift || puke "Missing template expansion hashref (\$form->prepare failed?)"; | ||
| 55 | |||
| 56 | my $tt2template = $self->{template} | ||
| 57 | || puke "Template Toolkit template not specified"; | ||
| 58 | my $tt2data = $self->{data} || {}; | ||
| 59 | my $tt2var = $self->{variable}; # optional var for nesting | ||
| 60 | |||
| 61 | if ($tt2var) { | ||
| 62 | $tt2data->{$tt2var} = $tvar; | ||
| 63 | } else { | ||
| 64 | $tt2data = { %$tt2data, %$tvar }; | ||
| 65 | } | ||
| 66 | my $tt2output; # growing a scalar is so C-ish | ||
| 67 | |||
| 68 | $self->{engine}->process($tt2template, $tt2data, \$tt2output) | ||
| 69 | || puke $self->{engine}->error(); | ||
| 70 | |||
| 71 | # string HTML output | ||
| 72 | return $tt2output; | ||
| 73 | } | ||
| 74 | |||
| 75 | 1; | ||
| 76 | __END__ |