Apache2::Controller::Render::Template - A2C render() with Template Toolkit


Version 1.001.001


 # apache2 config file

 PerlLoadModule Apache2::Controller::Directives
 PerlLoadModule Apache2::Controller::DBI::Connector

 # location of templates - must be defined
 A2C_Render_Template_Path  /var/myapp/templates /var/myapp/template_components

 <Location /foo>
    SetHandler modperl
    PerlInitHandler             MyApp::Dispatch::Foo

    # set directives A2C_DBI_DSN, etc. 
    PerlHeaderParserHandler     Apache2::Controller::DBI::Connector

See Apache2::Controller::Dispatch for A2C Dispatch implementations.

See Apache2::Controller::Directives and Apache2::Controller::DBI::Connector.

 package MyApp::C::Bar;  # let's assume this controller was dispatched

 use strict;
 use warnings;

 use base qw(

 use Apache2::Const -compile => qw( HTTP_OK );

 sub allowed_methods {qw( default )}

 sub default {
    my ($self, @first, @last) = @_;
    my @path_args = $self->my_detaint_path_args('name'); # from $self->{path_args}

    $self->{stash}{creditcards} = $self->pnotes->{a2c}{dbh}->fetchall_arrayref(
        q{  SELECT ccnum, exp, addr1, zip, cac 
            FROM customer_credit_cards 
            WHERE lname = ? AND fname = ?
        }, undef, @path_args

    # request was like

    $self->render();    # renders /var/myapp/templates/foo/default.html
    return Apache2::Const::HTTP_OK;


 [%# /var/myapp/templates/foo/default.html %]
 <p>Here is the credit card info you requested for 
 everyone named [% path_args.reverse.join(' ') %]:</p>
 [% FOREACH card = creditcards %]
    [% FOREACH field = ['ccnum','exp','addr1','zip','cac'] %]
    <li><strong>[% field %]:</strong> [% card.$field %]</li>
    [% END %]
 [% END %]
 [%# end template toolkit file %]


This module provides a nice rendering mechanism for Apache2::Controller.


You can specify options for Template in one of two ways:


By using "A2C_Render_Template_Opts" in Apache2::Controller::Directives:

 <Location '/foo'>
     A2C_Render_Template_Opts INTERPOLATE 1
     A2C_Render_Template_Opts PRE_PROCESS header
     A2C_Render_Template_Opts POST_CHOMP  1

METHOD template_options()

Or by implementing <template_options> in your controller:

 package MyApp::Controller;
 use base qw( Apache2::Controller Apache2::Controller::Render::Template );
 sub allowed_methods {qw( default )}

 sub template_options {
     my ($self) = @_;
     return {
         INTERPOLATE => 1,
         PRE_PROCESS => 'header',
         POST_CHOMP  =. 1,

 sub default { 
    # ...


We don't assign any stash functions by default. If you want to assign consistent stash functions in your controller, overload render(), assign them, and then call SUPER::render().

 package MyApp::ControllerBase;
 use base qw( Apache2::Controller Apache2::Controller::Render::Template );
 use HTML::Entities;

 sub render {
     my ($self) = @_;
     $self->{stash}{encode_entities} = \&encode_entities;

 package MyApp::Controller::Somewhere;
 use base qw( MyApp::ControllerBase );
 # ...
 sub someuri {
     my ($self, @path_args) = @_;
     return Apache2::Const::HTTP_OK;



render() accumulates template output into a variable before printing, so it may use a lot of memory if you expect a large data set.

It does this so it can intercept Template errors and kick up an exception to be printed using your error templates. See error().


So if you are planning to get a large data set, you probably want to use $self->render_fast() and put the database query handle somewhere in $self->{stash} and call fetchrow() in a Template block.

With render_fast(), Template->process() outputs directly to Apache2::Request->print(). So if a Template error is encountered, some output may have already been sent to the browser, resulting in a completely screwed up screen when the exception is kicked back up to the server.

Tip: if you plan to use render_fast(), write a test suite that tests the output of your page.

Of course you could bypass rendering altogether and just use $self->print(). (Remember that $self is normally subclassed in Apache2::Request which magically delegates to $self->{r}.) Or maybe you should implement an ajax style control in the template and put a limit frame on the query above, or use a paging lib, etc. ...


If your template directory contains a subdirectory named 'error', then when the controller throws an exception, the exception object will be passed to a selected error template as 'X' in the stash. It also sets status (number) and status_line (from HTTP::Status::status_message() or from the values set in the Apache2::Controller::X exception).

If you have a template $template_dir/error/$status.html, where $status is the numeric http status code, then it will use that template.

For example:

 203 HTTP_NON_AUTHORITATIVE     => error/203.html
 400 HTTP_BAD_REQUEST           => error/400.html
 404 NOT_FOUND                  => error/404.html
 500 HTTP_INTERNAL_SERVER_ERROR => error/500.html

For example, $template_dir/error/400.html or $template_dir/error/403.html.

Otherwise it will look for $template_dir/error/default.html and try to use that, otherwise it will give up.

error() remembers across requests whether you do or don't have error templates for certain messages in the appropriate template directory, so it will be faster the second time around if you use error/default.html.

For a reference list of status and messages, see Apache2::Controller.

Since render_fast() is incompatible if a template rendering error occurs, render_fast() turns off the use of error() and relies on standard Apache2 error messages (or the custom message set in the exception object) and relies on the browser to display them.


This is called internally by the render methods, but you can use it to figure out the default template from where you are.

To override the auto-select template, just set $self->{template} before you call <render()>.

It looks for templates in a computed directory. The directory where it looks will always be the directory set with the A2C_Render_Template_Path directive in the config file, appended with the current request location, i.e. the directory of the Location directive in the config file, appended with relative_uri, appended with method name and '.html'.

 A2C_Render_Template_Path + location + relative_uri + method.html

For example, the sequence in SYNOPSIS above renders the file /var/myapp/templates/foo/default.html .

Suppose the dispatch class above dispatches sub-path uris starting with 'bar/biz' to another controller. That controller would look for templates in the directory /var/myapp/templates/foo/bar/biz/methodname.html.



 location = /foo

 relative_uri = bar/biz

 controller MyApp::C::Foo::Bar::Biz  # mapped in your A2C Dispatch

 found method = baz

 path_args = [ boz, noz ]

 template = /var/myapp/templates + /foo + /bar/biz + /baz.html


$self->{relative_uri} is the uri relative to the location, so in other words:

  location + relative_uri == full uri - path args

See Apache2::Controller::Dispatch::Simple.


Get the Template object set up with the appropriate include directory set from the directive <A2C_Render_Template_Path>.

Directive A2C_Render_Template_Opts sets default new() options for Template.






Mark Hedges, <hedges at--!>


Copyright 2008-2010 Mark Hedges, all rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

This software is provided as-is, with no warranty and no guarantee of fitness for any particular purpose.