Extending HTML::Template

Includes via HTTP

HTML::Template lets you do includes with the <TMPL_INCLUDE "filename.tmpl"> syntax. But what if that file isn't on your local machine ? Just add custom filter for your templates and implement a new tag without touching the inner workings of HTML::Template.

Just do

my $tmpl = HTML::Template->new(filename => "filename.tmpl", filter => \&TemplateTools::http_include);
and replace your <TMPL_INCLUDE "filename.tmpl"> with <TMPL_HTTP_INCLUDE "http://server/filename.tmpl">.

The nice thing is that the new tag is completely independent of the Template module and should also work with replacement modules for HTML::Template such as HTML::Template::Compiled.

Download: TemplateTools.pm.

package TemplateTools;
use strict;
use LWP;
sub http_include {
 my $text_ref = shift;
 $$text_ref =~ s/<TMPL_HTTP_INCLUDE\s+"([^"]*)"\s*>/get_http($1)/ige;
}
sub get_http {
 my $url = shift;
 if ($url !~ /^http/) {
 my $domain = $ENV{SERVER_NAME} || 'localhost';
 $url = 'http://' . $domain . $url if ($url !~ /^http/);
 }
 my $browser = LWP::UserAgent->new( max_redirect => 0 );
 $browser->agent('TMPL_HTTP_INCLUDE');
 my $doc = $browser->request(HTTP::Request->new(GET => $url));
 return '' if ($doc->is_error());
 return $doc->content();
}
1;

 


Last updated: 19. Nov 2013
Page maintained by Jan Willamowius
Imprint/Impressum · Privacy/Datenschutz
 
English: Home | Linux | Perl | Java | Eiffel | Books | Music | Jan Willamowius | Updates | Site Map
Deutsch: Home | Badminton | ISBN-Suche | Musik-Suche | Rezepte | Jan Willamowius