| 1 | ##-*- Mode: CPerl -*- | ||
| 2 | |||
| 3 | ## File: DDC::Format::Template.pm | ||
| 4 | ## Author: Bryan Jurish <moocow@cpan.org> | ||
| 5 | ## Description: | ||
| 6 | ## + DDC Query utilities: output formatting: Template-based | ||
| 7 | ##====================================================================== | ||
| 8 | |||
| 9 | package DDC::Format::Template; | ||
| 10 | use Template; | ||
| 11 | use Carp; | ||
| 12 | use strict; | ||
| 13 | |||
| 14 | ##====================================================================== | ||
| 15 | ## Globals | ||
| 16 | our @ISA = qw(DDC::Format); | ||
| 17 | |||
| 18 | ##====================================================================== | ||
| 19 | ## Constructors, etc. | ||
| 20 | |||
| 21 | ## $fmt = $CLASS_OR_OBJ->new(%args) | ||
| 22 | ## + %args: | ||
| 23 | ## ( | ||
| 24 | ## src => $src, ##-- template source (filename, fh, or string ref) | ||
| 25 | ## config => \%ttconfig, ##-- see Template(3pm) | ||
| 26 | ## vars => \%vars, ##-- extra vars | ||
| 27 | ## tmpl => $template, ##-- Template object (overrides \%ttconfig) | ||
| 28 | ## ) | ||
| 29 | sub new { | ||
| 30 | my $that = shift; | ||
| 31 | my $fmt = bless { | ||
| 32 | src=>undef, | ||
| 33 | config=>{ | ||
| 34 | INTERPOLATE => 1, | ||
| 35 | PRE_CHOMP => 0, | ||
| 36 | POST_CHOMP => 1, | ||
| 37 | EVAL_PERL => 1, | ||
| 38 | ABSOLUTE => 1, | ||
| 39 | }, | ||
| 40 | vars => {}, | ||
| 41 | tmpl => undef, | ||
| 42 | @_ | ||
| 43 | }, ref($that)||$that; | ||
| 44 | if (!$fmt->{tmpl}) { | ||
| 45 | $fmt->{tmpl} = Template->new($fmt->{config}) | ||
| 46 | or confess(__PACKAGE__ . "::new(): could note create Template object: $Template::ERROR"); | ||
| 47 | } | ||
| 48 | return $fmt; | ||
| 49 | } | ||
| 50 | |||
| 51 | ## $fmt = $fmt->reset() | ||
| 52 | ## + reset counters, etc. | ||
| 53 | #sub reset { | ||
| 54 | # return $_[0]->SUPER::reset(); | ||
| 55 | #} | ||
| 56 | |||
| 57 | ##====================================================================== | ||
| 58 | ## API | ||
| 59 | |||
| 60 | ## $str = $fmt->toString(\@hits) | ||
| 61 | sub toString { | ||
| 62 | my ($fmt,$hits) = @_; | ||
| 63 | my $vars = { fmt=>$fmt, hits=>$hits, %{$fmt->{vars}||{}} }; | ||
| 64 | my $tmpl = $fmt->{tmpl}; | ||
| 65 | my $out = ''; | ||
| 66 | |||
| 67 | ##-- Template Toolkit doesn't like leading underscores in hash keys if $Template::Stash::PRIVATE is defined | ||
| 68 | #$Template::Stash::PRIVATE = undef; | ||
| 69 | |||
| 70 | $tmpl->process($fmt->{src}, $vars, \$out) | ||
| 71 | or confess(__PACKAGE__ . "::toString(): template error: ".$tmpl->error); | ||
| 72 | |||
| 73 | return $out; | ||
| 74 | } | ||
| 75 | |||
| 76 | 1; ##-- be happy | ||
| 77 | |||
| 78 | __END__ |