NAME

Apache::SimpleTemplate

SYNOPSIS

in httpd.conf:

<Files *.stml>
  SetHandler perl-script
  PerlHandler +Apache::SimpleTemplate

  ### options (w/ defaults):
  #PerlSetVar SimpleTemplateCache 1
  #PerlSetVar SimpleTemplateReload 1
  #PerlSetVar SimpleTemplateDebug 0
  #PerlSetVar SimpleTemplateCascadeStatus 1
  #PerlSetVar SimpleTemplateBlockBegin "<%"
  #PerlSetVar SimpleTemplateBlockEnd "%>"
  #PerlSetVar SimpleTemplateContentType "text/html"
</Files>

### have index.stml files handle a request for a directory name.
#DirectoryIndex index.html index.stml

<Location /example>
  SetHandler perl-script
  PerlHandler +Apache::SimpleTemplate
  PerlSetVar SimpleTemplateFile "/templates/example.stml"
</Location>

in a template:

<%! _perl_definitions_or_declarations_ %>

compiles the code once. (the code block is replaced by nothing.)
can be used for defining subroutines, 'use' calls, declaring and 
populating variables/hashes/etc.

<% _perl_code_ %>

executes the perl code. (this block is replaced by nothing.)
can also declare variables for use within the template.

<%= _a_perl_expression_ %>

evaluates the perl expression, and the block gets replaced by 
the expression's value.

'<%+ %>' is the same as '<%= %>', but the output gets url-encoded.
(mnemonic: '+' is a space in a url-encoded string.)

'<%^ %>'is the same as '<%= %>', but the output gets html-escaped.
(mnemonic: '^' looks like the '<' and '>' that get replaced.)

'<%\ %>'is the same as '<%= %>', except single-quotes get escaped.
(useful for javascript. "'" becomes "\'" and "\" becomes "\\".)

<%- _a_comment_ %>

is ignored and replace by nothing.
(mnemonic: "-" as in "<!-- html comments -->".)

<%# _comment_out_text_and/or_template_blocks_ #%>

comment out larger areas of templates, including code blocks.
NB: the '#' on the closing tag, as this is the only tag which can 
wrap other tags.

<% $s->include('/dir/file.stml') %>

includes another file or parsed-template in place of this.

<%= $$inref{foo}; %>

prints the value of the CGI/form input variable 'foo'.

<% $s->header('Location','/'); $s->status(302); return; %>

ends execution of the template and redirects browser to '/'.

<% $s->content_type('text/xml'); %>

sets our content-type to 'text/xml' instead of default 'text/html';

<%: _perl_code_ %> DEPRECATED

evaluates the perl code, and the block gets replaced by the last
value returned in the perl code, or $out if defined. (included
mostly for backward compatability-- it's better to use a mixture
of <% %> and <%= %> blocks.)
(mnemonic: '<%: %>' is like a combination of '<% %>' and '<%= %>'.)

DESCRIPTION

Apache::SimpleTemplate is *another* Template-with-embedded-Perl package for mod_perl. It allows you to embed blocks of Perl code into text documents, such as HTML files, and have this code executed upon HTTP request. It should take moments to set-up and learn; very little knowledge of mod_perl is necessary, though some knowledge of Apache and perl is assumed.

This module is meant to be a slim and basic alternative to more fully featured packages like Apache::Embperl, Apache::ASP, or TemplateToolkit, and more of a mod_perl counterpart to JSP or PHP. You may wish to compare approaches and features of the other perl templating schemes, and consider trade-offs in funcionality, implementation time, speed, memory consumption, etc. This module's relative lack of "features" is meant to improve both its performance and its flexibility.

Apache::SimpleTemplate has no added programming syntax, relying simply on perl itself for all programming logic in the templates. It should run with a very small memory footprint and little processing over-head. Templates get compiled into perl packages (or subroutines), and the caching and preloading options can help you increace speed and reduce memory consumption. SimpleTemplate is also designed for extension through subclasses, into which you can add the functionality you want.

INSTALLATION

The only requirement is mod_perl. To install Apache::SimpleTemplate, run:

perl Makefile.PL
make
make install

Then, to test it with Apache/mod_perl:

1) put the httpd.conf lines above into your httpd.conf
2) restart apache
3) try putting an example template from below into your document root
4) point your browser at the example

EXAMPLES

template "example.stml"

<%!
    my $foo = 'working!';
    sub not_installed_properly { return $foo;} 
%>
<html>
<body bgcolor="ffffff">

<h2>Apache::SimpleTemplate seems to be <%= &not_installed_properly(); %> </h2>

</body>
</html>

template "/printenv.stml"

<table border=3>
    <tr><th colspan=2 align=left>Environment variables</th></tr>

    <%  foreach my $e (sort keys(%ENV)) {   %>
          <tr>
            <td><strong><%=$e%></strong></td>
            <td><%=$ENV{$e};%></td>
          </tr>
    <%  }  %>
</table>

<table border=3>
    <tr><th colspan=2 align=left>CGI Arguments</th></tr>

    <%  foreach my $e (sort keys %$inref) {  %>
          <tr>
            <td><strong><%=$e%></strong></td>
            <td><%=$$inref{$e};%></td>
          </tr>
    <%  }  %>
</table>

subclass "MySimpleTemplate"

# in httpd.conf should set the handler: "PerlHandler +MySimpleTemplate"
# in your template you can call: "<%= $s->my_method %>"

package MySimpleTemplate;
use Apache::SimpleTemplate ();
our @ISA = qw(Apache::SimpleTemplate);

# handler() must be defined, as it is not a method.
# instantiate this class, and call SimpleTemplate's handler:
sub handler {
    my $r = shift;
    my $s = new MySimpleTemplate($r);
    #$s->block_begin('<%');
    #$s->block_end('%>');

    # you can make additional steps/logic here, including:
    #     set $s->file() for a template to use
    #     change $s->status()
    #     add headers w/ $s->header()

    return Apache::SimpleTemplate::handler($r, $s);
}

sub my_method {
    my $self = shift;
    return 'this is my_method.';
}
1;

Use in a CGI script or other code

#!/usr/bin/perl
# 
# example using SimpleTemplate in other code
#

# (could use your subclass here instead.)
use Apache::SimpleTemplate;              
my $s = new Apache::SimpleTemplate();

#### options: (caching won't do anything usefule in CGI mode.)
#$s->block_begin('<%');
#$s->block_end('%>');
#$s->debug(0);
$s->cache(0);
$s->reload(0);

#### call as a CGI (will get headers and status set):
#$s->content_type('text/html');
$s->file('/dir/file.stml');
exit &Apache::SimpleTemplate::handler();

#### or non-CGI use, just get the rendered page:
# $s->render('/full/path/to/file.stml');
# print ${ $s->{out} };

VARIABLES & FUNCTIONS

variables in templates:

$r            - this instance of 'Apache', i.e. the request object.
$s            - this instance of 'Apache::SimpleTemplate' (or your subclass)
$inref        - a reference to a hash containing the CGI/form input args
$____st_*     - these names are reserved for use inside the parsing function.

constructor and getters/setters:

$s = new Apache::SimpleTemplate($r)  -- pass the Apache request object, $r.
                                        parses CGI params.
$s = new Apache::SimpleTemplate($in) -- pass me a hash of CGI params.
$s = new Apache::SimpleTemplate()    -- parses params from $ENV{QUERY_STRING}

$s->block_begin()        -- get or set the beginning delimiter
$s->block_begin('<%')

$s->block_end()          -- get or set the ending delimiter
$s->block_end('%>')

$s->file()               -- get or set a file for rendering
$s->file('/foo.stml')

$s->debug()              -- get or set the debug level (0=quiet - 3=verbose)
$s->debug(1)

$s->reload()             -- get or set the reload flag (0 or 1)
$s->reload(1)

$s->cache()              -- get or set the caching flag (0 or 1)
$s->cache(1)

$s->cascade_status()     -- get or set flag for cascading status codes 
$s->cascade_status(0)       from included templates

other methods/functions (mostly useful in templates):

$s->content_type('text/xml')   -- set our content-type to something
                                  (must be done before any call to flush().)
$s->status(302)                -- set our status to something other than 200
                                  (must be done before any call to flush().)
$s->header($name,$value)       -- add an outgoing header. (can add multiple 
                                  of the same name.)
                                  (must be done before any call to flush().)

return                         -- stop running this template (within <% %>)

$s->encode($string)            -- url-encode the $string.
                                  &Apache::SimpleTemplate::encode($string)
$s->decode($string)            -- url-decode the $string.
                                  &Apache::SimpleTemplate::decode($string)
$s->escape($string)            -- html-escape the $string.
                                  &Apache::SimpleTemplate::escape($string)
$s->quote_escape($string)      -- single-quote-escape the $string.
                                  &Apache::SimpleTemplate::quote_escape($string)

$s->preload($file)             -- preload the template in $file, a full
                                  path which must match the DOCUMENT_ROOT.
                                  (for use in a startup.pl file.)

$s->include('/dir/file')       -- include another document/template.
                                  the path is relative to the DOCUMENT_ROOT

$s->print(...)                 -- print out something from within <% %>.
$s->flush()                    -- flush the print buffer (within <% %>).
                                  (sends HTTP headers on the first call.)

deprecated and removed vars and functions.

$out          - deprecated template variable.
                a <%: %> block of code could use this for the output, 
                instead of the last value returned by the block. 
                use <% %> or <%= %> blocks as needed instead.

$headerref    - removed, use $s->header() instead.
$status       - removed, use $s->status() instead.
$content_type - removed, use $s->content_type() instead.

Apache::SimpleTemplate::include() -- static calls no longer work.
                instantiate if necessary, and use $s->include() instead.
                (shouldn't have been included in the first place, as they
                would not follow any settings other than defaults.)

PerlSetVar options

SimpleTemplateBlockBegin    -- the delim for a code block's end ['<%']
SimpleTemplateBlockEnd      -- the delim for a code block's start ['%>']

SimpleTemplateCache         -- keep templates in memory? [1]
SimpleTemplateReload        -- check templates for changes? [1]
SimpleTemplateDebug         -- level of debug msgs in error_log (0-3) [0]
                               (if >= 1, compile errors go to the browser.)

SimpleTemplateContentType   -- the default content_type ['text/html']
SimpleTemplateCascadeStatus -- set to 0 if you do not want included 
                               templates to affect the response status.
SimpleTemplateFile          -- template file location (w/in doc_root)
                               probably useful only within a <Location>.
                               [the incoming request path]

OTHER TIDBITS

template processing

Any errors in evaluating a code block should get logged to the error_log.
The compilation process tries to keep the line numbers consistent with
the template, but <%! %> declarations/definitions that are not at the
top of the template may throw line numbers off.

Any additional variables you wish to use must be declared (with 'my').
If you declare them in <%! %> or <% %> blocks, they will be accessible
in later blocks.

Included sub-templates receive the same instance of $s, so they have the 
same $inref, etc. Thus, they can also set headers, change status, etc.
(Turn off "cascade_status" to prevent the latter.)

template debugging

SimpleTemplateDebug / $s->debug() values have the following meanings
  0 quiet, errors logged to error_log
  1 quiet, errors also sent to browser
  2 info on requests, includes, status codes, etc.
  3 info on template compilation. (noisy)
  4 verbose info on template compilation. (extremely noisy)

You can also always log your own messages to the error_log from 
within your templates, eg: <% print STDERR "some message" %>.

performance notes

Templates are compiled into perl packages (or anonymous subroutines if
there is no <%! %> block.) Caching of templates, which is on by default,
will help speed performance greatly. The only reason you might want to
turn it off is if you have many, many templates and don't want them 
always kept around in memory.

Preloading via preload() in a startup.pl file is a way to save more 
memory (the template will get loaded before the webserver forks its
children, thus keeping the template in memory shared by all the procs.)
This also will improve speed a bit, as each newly spawned webserver
proc will not need to load the template anew. 

preload() may be used even with caching off (0), if you have a handful of
templates you want to cache but many others you do not.

Turning SimpleTemplateReload to off (0) will speed things a little bit,
as SimpleTemplate will not check the file for updates with every request.
However, if you are using caching/preloading and SimpleTemplateCache is 
off (0), Apache must be restarted to see template changes.

Finally, the regular CGI mode will probably be very slow, so you may
want only to use it when testing something (a cached template or another
module/subclass), or when using a host without mod_perl installed.

New in 0.04

$s->print and $s->flush methods. Option to have errors in included 
templates not bubble up and cause whole page to fail.

Defaults delims are now the more conventional '<%' and '%>'.
Users still wanting '{{' and '}}' can set the 
SimpleTemplateBlockBegin and SimpleTemplateBlockEnd variables.

$status, $headerref, $content_type not supported in templates.

Note for users of previous versions 0.01 or 0.02

Anyone switching from a version previous to 0.03 should note that the
default <% _perl_block_ %> behavior has changed. The behavior of the
new <%: %> tag should be functionally equivalent, so switching all
your tags to this should be an easy fix. (try 
"perl -pi~ -e 's/\{\{/\<\%\:/g' __your_files__", and
"perl -pi~ -e 's/\}\}/\%\>/g' __your_files__".)

The imperfect backward-compatablility seemed worth it for the more
intuitive behavior of the tags, and for the consistency with other
templating mechanisms like jsp/asp.

Note also the preferred $s->status(), $s->content_type() and
$s->header() calls rather than $status, $content_type, $headerref.

VERSION

Version 0.05, 2003-March-30.

AUTHOR

peter forty 
Please send any comments or suggestions to
mailto: apache-simple-template _at_ peter.nyc.ny.us

The homepage for this project is: 
http://peter.nyc.ny.us/simpletemplate/

COPYRIGHT (c) 2001-2003

This is free software with absolutely no warranty.
You may use it, distribute it, and/or modify 
it under the same terms as Perl itself.

SEE ALSO

perl, mod_perl.