| 1 | package OpenInteract2::ContentGenerator::TextTemplate; | ||
| 2 | |||
| 3 | # $Id: TextTemplate.pm,v 1.10 2005/03/17 14:58:01 sjn Exp $ | ||
| 4 | |||
| 5 | use strict; | ||
| 6 | use base qw( OpenInteract2::ContentGenerator ); | ||
| 7 | |||
| 8 | use Log::Log4perl qw( get_logger ); | ||
| 9 | use OpenInteract2::Constants qw( :log ); | ||
| 10 | use OpenInteract2::ContentGenerator::TemplateSource; | ||
| 11 | use OpenInteract2::Context qw( CTX ); | ||
| 12 | use OpenInteract2::Exception qw( oi_error ); | ||
| 13 | use Text::Template; | ||
| 14 | |||
| 15 | $OpenInteract2::ContentGenerator::TextTemplate::VERSION = sprintf("%d.%02d", q$Revision: 1.10 $ =~ /(\d+)\.(\d+)/); | ||
| 16 | |||
| 17 | my ( $log ); | ||
| 18 | |||
| 19 | # Text::Template doesn't seem to use the same architecture as TT, so | ||
| 20 | # it doesn't make sense to create a template object in initialize() | ||
| 21 | # and reuse it. | ||
| 22 | |||
| 23 | sub initialize { | ||
| 24 | my $log_init = get_logger( LOG_INIT ); | ||
| 25 | $log_init->is_info && | ||
| 26 | $log_init->info( "Called initialize() for Text::Template CG (no-op)" ); | ||
| 27 | } | ||
| 28 | |||
| 29 | sub generate { | ||
| 30 | my ( $self, $template_config, $template_vars, $template_source ) = @_; | ||
| 31 | $log ||= get_logger( LOG_TEMPLATE ); | ||
| 32 | |||
| 33 | # TODO: Check for cached content... | ||
| 34 | |||
| 35 | my ( $source_type, $source ) = | ||
| 36 | OpenInteract2::ContentGenerator::TemplateSource->identify( $template_source ); | ||
| 37 | if ( $source_type eq 'NAME' ) { | ||
| 38 | my ( $template, $filename, $modified ) = | ||
| 39 | OpenInteract2::ContentGenerator::TemplateSource->load_source( $source ); | ||
| 40 | $source_type = 'STRING'; | ||
| 41 | $source = $template; | ||
| 42 | $log->is_debug && | ||
| 43 | $log->debug( "Loading from name $source" ); | ||
| 44 | } | ||
| 45 | else { | ||
| 46 | $log->is_debug && | ||
| 47 | $log->debug( "Loading from source $source_type" ); | ||
| 48 | } | ||
| 49 | $template_config->{TYPE} = $source_type; | ||
| 50 | $template_config->{SOURCE} = ( ref $source eq 'SCALAR' ) | ||
| 51 | ? $$source : $source; | ||
| 52 | my $template = Text::Template->new( %{ $template_config } ); | ||
| 53 | unless ( $template ) { | ||
| 54 | my $msg = "Failed to create template parsing object: " . | ||
| 55 | $Text::Template::ERROR; | ||
| 56 | $log->error( $msg ); | ||
| 57 | oi_error $msg; | ||
| 58 | } | ||
| 59 | my $content = $template->fill_in( HASH => $template_vars ); | ||
| 60 | unless ( $content ) { | ||
| 61 | my $msg = "Failed to fill in template: $Text::Template::ERROR"; | ||
| 62 | $log->error( $msg ); | ||
| 63 | oi_error $msg ; | ||
| 64 | } | ||
| 65 | |||
| 66 | # TODO: Cache content before returning | ||
| 67 | |||
| 68 | return $content; | ||
| 69 | } | ||
| 70 | |||
| 71 | 1; | ||
| 72 | |||
| 73 | __END__ |