NAME
CGI::Application::Plugin::TT - Add Template Toolkit support to CGI::Application
SYNOPSIS
use base qw(CGI::Application);
use CGI::Application::Plugin::TT;
sub myrunmode {
my $self = shift;
my %params = (
email => 'email@company.com',
menu => [
{ title => 'Home', href => '/home.html' },
{ title => 'Download', href => '/download.html' },
],
session_obj => $self->session,
);
return $self->tt_process('template.tmpl', \%params);
}
DESCRIPTION
CGI::Application::Plugin::TT adds support for the popular Template Toolkit engine to your CGI::Application modules by providing several helper methods that allow you to process template files from within your runmodes.
It compliments the support for HTML::Template that is built into CGI::Application through the load_tmpl method. It also provides a few extra features than just the ability to load a template.
METHODS
tt_process
This is a simple wrapper around the Template Toolkit process method. It accepts zero, one or two parameters; an optional template filename, and an optional hashref of template parameters (the template filename is optional, and will be autogenerated by a call to $self->tt_template_name if not provided). The return value will be a scalar reference to the output of the template.
package My::App::Browser
sub myrunmode {
my $self = shift;
return $self->tt_process( 'Browser/myrunmode.tmpl', { foo => 'bar' } );
}
sub myrunmode2 {
my $self = shift;
return $self->tt_process( { foo => 'bar' } ); # will process template 'My/App/Browser/myrunmode2.tmpl'
}
tt_config
This method can be used to customize the functionality of the CGI::Application::Plugin::TT module, and the Template Toolkit module that it wraps. The recommended place to call tt_config
is as a class method in the global scope of your module (See SINGLETON SUPPORT for an explanation of why this is a good idea). If this method is called after a call to tt_process or tt_obj, then it will die with an error message.
It is not a requirement to call this method, as the module will work without any configuration. However, most will find it useful to set at least a path to the location of the template files ( or you can set the path later using the tt_include_path method).
our $TEMPLATE_OPTIONS = {
COMPILE_DIR => '/tmp/tt_cache',
DEFAULT => 'notfound.tmpl',
PRE_PROCESS => 'defaults.tmpl',
};
__PACKAGE__->tt_config( TEMPLATE_OPTIONS => $TEMPLATE_OPTIONS );
The following parameters are accepted:
- TEMPLATE_OPTIONS
-
This allows you to customize how the Template object is created by providing a list of options that will be passed to the Template constructor. Please see the documentation for the Template module for the exact syntax of the parameters, or see below for an example.
- TEMPLATE_NAME_GENERATOR
-
This allows you to provide your own method for auto-generating the template filename. It requires a reference to a function that will be passed the $self object as it's only parameter. This function will be called everytime $self->tt_process is called without providing the filename of the template to process. This can standardize the way templates are organized and structured by making the template filenames follow a predefined pattern.
The default template filename generator uses the current module name, and the name of the calling function to generate a filename. This means your templates are named by a combination of the module name, and the runmode.
- TEMPLATE_PRECOMPILE_DIR
-
This options allows you to specify a directory (or an array of directories) to search when this module is loaded and then compile all files found into memory. This provides a speed boost in persistant environments (mod_perl, fast-cgi) and can improve memory usage in environments that use shared memory (mod_perl).
- TEMPLATE_PRECOMPILE_FILETEST
-
This option allows you to specify exactly which files will get compiled when using the TEMPLATE_PRECOMPILE_DIR option. You can provide it with one of 3 different variable types:
- STRING
-
A filename extension that can specify what type of files will be loaded (eg 'tmpl').
- REGEXP
-
Filenames that match the regular expression will be precompiled ( eg qr/\.(tt|tmpl|html)$/ ).
- CODEREF
-
A code reference that will be called once for each filename and directory found, and if it returns true, the template will be precompiled (eg sub { my $file = shift; ... } ).
tt_obj
This method will return the underlying Template Toolkit object that is used behind the scenes. It is usually not necesary to use this object directly, as you can process templates and configure the Template object through the tt_process and tt_config methods. Every call to this method will return the same object during a single request.
It may be useful for debugging purposes.
tt_params
This method will accept a hash or hashref of parameters that will be included in the processing of every call to tt_process. It is important to note that the parameters defined using tt_params will be passed to every template that is processed during a given request cycle. Usually only one template is processed per request, but it is entirely possible to call tt_process multiple times with different templates. Everytime tt_process is called, the hashref of parameters passed to tt_process will be merged with the parameters set using the tt_params method. Parameters passed through tt_process will have precidence in case of duplicate parameters.
This can be useful to add global values to your templates, for example passing the user's name automatically if they are logged in.
sub cgiapp_prerun {
my $self = shift;
$self->tt_params(username => $ENV{REMOTE_USER}) if $ENV{REMOTE_USER};
}
tt_clear_params
This method will clear all the currently stored parameters that have been set with tt_params.
tt_pre_process
This is an overridable method that works in the spirit of cgiapp_prerun. The method will be called just before a template is processed, and will be passed the template filename, and a hashref of template parameters. It can be used to make last minute changes to the template, or the parameters before the template is processed.
sub tt_pre_process {
my ($self, $file, $vars) = @_;
$vars->{user} = $ENV{REMOTE_USER};
return;
}
If you are using CGI::Application 4.0 or greater, you can also register this as a callback.
__PACKAGE__->add_callback('tt_pre_process', sub {
my ($self, $file, $vars) = @_;
$vars->{user} = $ENV{REMOTE_USER};
return;
});
tt_post_process
This, like it's counterpart cgiapp_postrun, is called right after a template has been processed. It will be passed a scalar reference to the processed template.
sub tt_post_process {
my ($self, $htmlref) = shift;
require HTML::Clean;
my $h = HTML::Clean->new($htmlref);
$h->strip;
my $newref = $h->data;
$$htmlref = $$newref;
return;
}
If you are using CGI::Application 4.0 or greater, you can also register this as a callback (See tt_pre_process for an example of how to use it).
tt_template_name
This method will generate a template name for you based on two pieces of information: the method name of the caller, and the package name of the caller. It allows you to consistently name your templates based on a directory hierarchy and naming scheme defined by the structure of the code. This can simplify development and lead to more consistent, readable code.
If you do not want the template to be named after the method that called tt_template_name, you can pass in an integer, and the method used to generate the template name will be that many levels above the caller. It defaults to zero.
For example:
package My::App::Browser
sub dummy_call {
my $self = shift;
return $self->tt_template_name(1); # parent callers name
}
sub view {
my $self = shift;
my $template;
$template = $self->tt_template_name; # returns 'My/App/Browser/view.tmpl'
$template = $self->dummy_call; # also returns 'My/App/Browser/view.tmpl'
return $self->tt_process($template, { var1 => param1 });
}
To simplify things even more, tt_process automatically calls $self->tt_template_name for you if you do not pass a template name, so the above can be reduced to this:
package MyApp::Example
sub view {
my $self = shift;
return $self->tt_process({ var1 => param1 }); # process template 'MyApp/Example/view.tmpl'
}
Since the path is generated based on the name of the module, you could place all of your templates in the same directory as your perl modules, and then pass @INC as your INCLUDE_PATH parameter. Whether that is actually a good idea is left up to the reader.
$self->tt_include_path(\@INC);
tt_include_path
This method will allow you to set the include path for the Template Toolkit object after the object has already been created. Normally you set the INCLUDE_PATH option when creating the Template Toolkit object, but sometimes it can be useful to change this value after the object has already been created. This method will allow you to do that without needing to create an entirely new Template Toolkit object. This can be especially handy when using the Singleton support mentioned below, where a Template Toolkit object may persist across many request. It is important to note that a call to tt_include_path will change the INCLUDE_PATH for all subsequent calls to this object, until tt_include_path is called again. So if you change the INCLUDE_PATH based on the user that is connecting to your site, then make sure you call tt_include_path on every request.
my $root = '/var/www/';
$self->tt_include_path( [$root.$ENV{SERVER_NAME}, $root.'default'] );
When called with no parameters tt_include_path returns an arrayref containing the current INCLUDE_PATH.
DEFAULT PARAMETERS
By default, the TT plugin will automatically add a parameter 'c' to the template that will return to your CGI::Application object $self. This allows you to access any methods in your CGI::Application module that you could normally call on $self from within your template. This allows for some powerful actions in your templates. For example, your templates will be able to access query parameters, or if you use the CGI::Application::Plugin::Session module, you can access session parameters.
Hello [% c.session.param('username') || 'Anonymous User' %]
<a href="[% c.query.self_url %]">Reload this page</a>
Another useful plugin that can use this feature is the CGI::Application::Plugin::HTMLPrototype plugin, which gives easy access to the very powerful prototype.js JavaScript library.
[% c.prototype.define_javascript_functions %]
<a href="#" onclick="javascript:[% c.prototype.visual_effect( 'Appear', 'extra_info' ) %] return false;">Extra Info</a>
<div style="display: none" id="extra_info">Here is some more extra info</div>
With this extra flexibility comes some responsibilty as well. It could lead down a dangerous path if you start making alterations to your object from within the template. For example you could call c.header_add to add new outgoing headers, but that is something that should be left in your code, not in your template. Try to limit yourself to pulling in information into your templates (like the session example above does).
EXAMPLE
In a CGI::Application module:
package My::App
use CGI::Application::Plugin::TT;
use base qw(CGI::Application);
# configure the template object once during the init stage
sub cgiapp_init {
my $self = shift;
# Configure the template
$self->tt_config(
TEMPLATE_OPTIONS => {
INCLUDE_PATH => '/path/to/template/files',
POST_CHOMP => 1,
FILTERS => {
'currency' => sub { sprintf('$ %0.2f', @_) },
},
},
);
}
sub cgiapp_prerun {
my $self = shift;
# Add the username to all templates if the user is logged in
$self->tt_params(username => $ENV{REMOTE_USER}) if $ENV{REMOTE_USER};
}
sub tt_pre_process {
my $self = shift;
my $template = shift;
my $params = shift;
# could add the username here instead if we want
$params->{username} = $ENV{REMOTE_USER}) if $ENV{REMOTE_USER};
return;
}
sub tt_post_process {
my $self = shift;
my $htmlref = shift;
# clean up the resulting HTML
require HTML::Clean;
my $h = HTML::Clean->new($htmlref);
$h->strip;
my $newref = $h->data;
$$htmlref = $$newref;
return;
}
sub my_runmode {
my $self = shift;
my %params = (
foo => 'bar',
);
# return the template output
return $self->tt_process('my_runmode.tmpl', \%params);
}
sub my_otherrunmode {
my $self = shift;
my %params = (
foo => 'bar',
);
# Since we don't provide the name of the template to tt_process, it
# will be auto-generated by a call to $self->tt_template_name,
# which will result in a filename of 'Example/my_otherrunmode.tmpl'.
return $self->tt_process(\%params);
}
SINGLETON SUPPORT
Creating a Template Toolkit object can be an expensive operation if it needs to be done for every request. This startup cost increases dramatically as the number of templates you use increases. The reason for this is that when TT loads and parses a template, it generates actual perlcode to do the rendering of that template. This means that the rendering of the template is extremely fast, but the initial parsing of the templates can be inefficient. Even by using the builting caching mechanism that TT provides only writes the generated perl code to the filesystem. The next time a TT object is created, it will need to load these templates from disk, and eval the sourcecode that they contain.
So to improve the efficiency of Template Toolkit, we should keep the object (and hence all the compiled templates) in memory across multiple requests. This means you only get hit with the startup cost the first time the TT object is created.
All you need to do to use this module as a singleton is to call tt_config as a class method instead of as an object method. All the same parameters can be used when calling tt_config as a class method.
When creating the singleton, the Template Toolkit object will be saved in the namespace of the module that created it. The singleton will also be inherited by any subclasses of this module. So in effect this is not a traditional Singleton, since an instance of a Template Toolkit object is only shared by a module and it's children. This allows you to still have different configurations for different CGI::Application modules if you require it. If you want all of your CGI::Application applications to share the same Template Toolkit object, just create a Base class that calls tt_config to configure the plugin, and have all of your applications inherit from this Base class.
SINGLETON EXAMPLE
package My::App;
use base qw(CGI::Application);
use CGI::Application::Plugin::TT;
My::App->tt_config(
TEMPLATE_OPTIONS => {
POST_CHOMP => 1,
},
);
sub cgiapp_prerun {
my $self = shift;
# Set the INCLUDE_PATH (will change the INCLUDE_PATH for
# all subsequent requests as well, until tt_include_path is called
# again)
my $basedir = '/path/to/template/files/',
$self->tt_include_path( [$basedir.$ENV{SERVER_NAME}, $basedir.'default'] );
}
sub my_runmode {
my $self = shift;
# Will use the same TT object across multiple request
return $self->tt_process({ param1 => 'value1' });
}
package My::App::Subclass;
use base qw(My::App);
sub my_other_runmode {
my $self = shift;
# Uses the TT object from the parent class (My::App)
return $self->tt_process({ param2 => 'value2' });
}
AUTHOR
Cees Hek <ceeshek@gmail.com>
BUGS
Please report any bugs or feature requests to bug-cgi-application-plugin-tt@rt.cpan.org
, or through the web interface at http://rt.cpan.org. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
CONTRIBUTING
Patches, questions and feedback are welcome.
SEE ALSO
CGI::Application, Template, perl(1)
LICENSE
Copyright (C) 2005 Cees Hek, All Rights Reserved.
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself.