Sergey Lepenkov
and 1 contributors


TemplateM - *ML templates processing module


Version 3.03


    use TemplateM;
    use TemplateM 'simple';

    my $template = new TemplateM(
            -url => 'http://localhost/foo.shtml',
            -utf8 => 1,
    my $template = new TemplateM( -file => 'ftp://login:password@' );
    my $template = new TemplateM( -file => 'foo.shtml' );
    my $template = new TemplateM( -file => \*DATA );


    my $block = $template->start( 'block_label' );
    $block->loop( foo => 'value1', bar => 'value2', ... );

    $template->stash( foo => 'value1', bar => 'value2', ... );
    $block->stash( baz => 'value1', ... );

    $template->ifelse( "ifblock_label", $predicate )
    $block->ifelse( "ifblock_label", $predicate )

    print $block->output;


    print $template->output;
    print $template->html( "Content-type: text/html\n\n" );

    $template->cast( {foo => 'value1', bar => 'value2', ... } );
    my %h = ( ... );
    $template->cast( \%h );

    $template->cast_loop ( "block_label", {foo => 'value1', bar => 'value2', ... } );
    $template->finalize ( "block_label" );

    $template->cast_if( "block_label", $predicate );


The TemplateM module means for text templates processing in XML, HTML, TEXT and so on formats. TemplateM is the alternative to most of standard modules, and it can accomplish remote access to template files, has simple syntax, small size and flexibility. Then you use TemplateM, functionality and data are completely separated, this is quality of up-to-date web-projects.



Set of methods prodiving process template's structures.


File or array of data which represents the set of instructions, directives and tags of markup languages and statistics.


Name of structure in a template for substitution. There are a number of directives:

    cgi, val, do, loop, if, endif, else, endelse


Structure is the tag or the group of tags in a template which defining a scope of substitution. The structure consist of tag <!-- --> and formatted content:


The structure can be simple or complex. Simple one is like this:

    <!-- cgi: foo -->
    <!-- val: bar -->

Complex structure is the group of simple structures which constitutive a "section"

    <!-- do: foo -->
        <!-- val: bar -->
    <!-- loop: foo -->

    even so:

    <!-- if: foo -->
    <!-- endif: foo -->
    <!-- else: foo -->
    <!-- endelse: foo -->


This is identifier of structure. E.g. foo, bar, baz

    <!-- cgi: foo -->



While defining use it can specify 2 accessible schemes - galore (default) or simple. It is not obligatory to point at default scheme.

Simple scheme is basic and defines using of basic methods:

cast, cast_if, cast_loop, finalize and html

Simple scheme methods is expedient for small-datasize projects.

Galore (default) scheme is the alternative for base scheme and it defines own set of methods:

stash, start, loop, finish, ifelse, output and html

In order to get knowing which of schemes is activated you need to invoke methods either module() or scheme()

    my $module = $template->module;
    my $module = $template->scheme;

In order to get know real module name of the used scheme it's enough to read property 'module' of $template object

    my $module = $template->{module};


Constructor new() is the principal method independent of selected scheme. Almost simple way to use the constructor is:

    my $template = new TemplateM( -template => "blah-blah-blah" );

This invoking takes directive to use simple text as template.

Below is the attribute list of constructor:


Asfile flag designates either path or filehandle to file is passed for reading from disk, bypassing the method of remote obtaining of a template.


Cache is the absolute or relative path to directory for cache files storage. This directory needs to have a permission to read and write files. When cache is missed caching is disabled. Caching on is recommended for faster module operations.

file, url, uri

Template filename is the filename, opened filehandler (GLOB) or locations of a template. Supports relative or absolute pathes, and also template file locator. Relative path can forestall with ./ prefix or without it. Absolute path must be forestall with / prefix. Template file locator is the URI formatted string. If the file is missed, it use "index.shtml" from current directory as default value.

Value represent "Uniform Resource Identifier references" as specified in RFC 2396 (and updated by RFC 2732). See URI for details.

HTTP header uses as value by default before main content template print (method html).

    my $template = new TemplateM( -header => "Content-type: text/html; charset=UTF-8\n\n");
    print $template->html;
login & password

User Login and user password are data for standard HTTP-authorization. Login and password will be used when the template defined via locator and when remote access is protected by HTTP-authorization of remote server. When user_login is missed the access to remote template file realizes simplified scheme, without basic HTTP-authorization.


Request method points to method of remote HTTP/HTTPS access to template page. Can take values: "GET", "HEAD", "PUT" or "POST". HEAD methods can be used only for headers getting.

onutf8 or utf8

onutf8 flag turn UTF8 mode for access to a file. The flag allow to get rid of a forced setting utf-8 flag for properties template and work by method Encode::_utf8_on()


HTTP content (template). This attribute has to be defined when template content is not able to get from a file or get it from remote locations. E.g. it has to be defined when a template selects from a database. Defining of this attribute means disabling of precompile result caching!


Timeout is the period of cache file keeping in integer seconds. When the value is missed cache file "compiles" once and will be used as template. Positive value has an effect only then template file is dynamic and it changes in time. Previous versions of the module sets value 20 instead 0 by default. It had to set the value -1 for "compilation" disabling. For current version of the module value can be 0 or every positive number. 0 is equivalent -1 of previous versions of the module.


Request code is the pointer to the subroutine must be invoked for HTTP::Request object after creation via method new.


    -reqcode => sub { 
        my $req = shift;
        $req-> ...
        return 1;

Response code is the pointer to the subroutine must be invoked for HTTP::Response after creation via calling $ua->request($req).


    -rescode => sub { 
        my $res = shift;
        $res-> ...
        return 1;

UserAgent code is the pointer to the subroutine must be invoked for LWP::UserAgent after creation via method new().


    -uacode => sub { 
        my $ua = shift;
        $ua-> ...
        return 1;

UserAgent options is the pointer to the hash containing options for defining parameters of UserAgent object's constructor. (See LWP::UserAgent)


    -uaopts => {
        agent                 => "Mozilla/4.0",
        max_redirect          => 10,
        requests_redirectable => ['GET','HEAD','POST'],
        protocols_allowed     => ['http', 'https'], # Required Crypt::SSLeay
        cookie_jar            => new HTTP::Cookies(
                file     => File::Spec->catfile("/foo/bar/_cookies.dat"),
                autosave => 1 
        conn_cache            => new LWP::ConnCache(),


It is enough to define the module with 'simple' parameter for using of basic methods.

    use TemplateM 'simple';

After that only basic metods will be automatically enabled.


Modification of labels (cgi labels)

    $template->cast({label1=>value1, label2=>value2, ... });

Label - name will be replaced with appropriate value in tag <!-- cgi: label -->


Value - Value, which CGI-script sets. Member of the label manpage


Block labels modification (val labels)

    $template->cast_loop (block_label, {label1=>value1, label2=>value2, ... }]);

Block label - Block identification name. The name will be inserted in tags <!-- do: block_label --> and <!-- loop: block_label --> - all content between this tags processes like labels, but the tag will be formed as <!-- val: label -->


Block finalizing


Block finalizing uses for not-processed blocks deleting. You need use finalizing every time you use blockes.


    $template->cast_if(ifblock_label, predicate);

Method analyses boolean value of predicate. If value is true, the method prints if-structure content only.

    <!-- if: label -->
        ... blah blah blah ...
    <!-- end_if: label -->

otherwise the method prints else-structure content only.

    <!-- else: label -->
        ... blah blah blah ...
    <!-- end_else: label -->


Template finalizing

    print $template->html(-header=>HTTP_header);
    print $template->html(HTTP_header);
    print $template->html;

The procedure will return formed document after template processing. if header is present as argument it will be added at the beginning of template's return.


It is enough to define the module with parameter 'galore' for using of galore scheme methods.

    use TemplateM;
    use TemplateM 'galore';


stash (or cast) method is the function of import variables value into template.

    $template->stash(title => 'PI' , pi => 3.1415926);

This example demonstrate how all of <!-- cgi: title --> and <!-- cgi: pi --> structures will be replaced by parameters of stash method invoking.

In contrast to default scheme, in galore scheme stash method process directives <!-- cgi: label --> only with defined labels when invoking, whereas cast method of default scheme precess all of directives <!-- cgi: label --> in template!

start and finish

Start method defines the beginning of loop, and finish method defines the end. Start method returns reference to the subtemplate object, that is all between do and loop directives.

    <!-- do: block_label -->
        ... blah blah blah ...
            <!-- val: label1 -->
            <!-- val: label2 -->
            <!-- cgi: label -->
        ... blah blah blah ...
    <!-- loop: block_label -->

    my $block = $template->start(block_label);

For acces to val directives it is necessary to use loop method, and for access to cgi directives use stash method.


The method takes as parameters a hash of arguments or a reference to this hash.

    $block->loop(label1 => 'A', label2 => 'B');
    $block->loop({label1 => 'A', label2 => 'B'});

Stash method also can be invoked in $block object context.

    $block->stash(label => 3.1415926);


    $template->ifelse("ifblock_label", $predicate)
    $block->ifelse("ifblock_label", $predicate)

Method is equal to cast_if method of default scheme. The difference, ifelse method can be processed with $template or $block, whereas cast_if method has deal with $template object.


The method returns result of template processing. Output method has deal with $template and $block object:



The method is completely equal to html method of default scheme.


In file:

    use TemplateM;

    my $tpl = new TemplateM(
        -file   => 'test.tpl',
        -asfile => 1,

        module  => (split(/\=/,"$tpl"))[0],
        version => $tpl->VERSION,
        scheme  => $tpl->scheme()." / ".$tpl->{module},
        date    => scalar(localtime(time())),

    my $row_box = $tpl->start('row');
    foreach my $row ('A'..'F') {
        my $col_box = $row_box->start('col');
        foreach my $col (1...6) {
            $col_box->loop( foo  => $row.$col );
                    ('A'..'F')[$col-1] ne $row
                    ('A'..'F')[6-$col] ne $row

    binmode STDOUT, ':raw';
    print $tpl->output();

In test.tpl file:

    *                    *
    *  Simple text file  *
    *                    *

    <!-- do: row -->
    |<!-- do: col --><!-- if: div --><!-- val: foo --><!-- endif: div -->
    <!-- else: div -->  <!-- endelse: div -->|<!-- loop: col --><!-- loop: row -->


    Module       : <!-- cgi: module -->
    Version      : <!-- cgi: version -->
    Scheme       : <!-- cgi: scheme -->
    Current date : <!-- cgi: date -->


    *                    *
    *  Simple text file  *
    *                    *


    |  |A2|A3|A4|A5|  |
    |B1|  |B3|B4|  |B6|
    |C1|C2|  |  |C5|C6|
    |D1|D2|  |  |D5|D6|
    |E1|  |E3|E4|  |E6|
    |  |F2|F3|F4|F5|  |


    Module       : TemplateM
    Version      : 3.02
    Scheme       : galore / GaloreWin32
    Current date : Sat Dec 18 12:37:10 2010


The module can be used with SSI directives together, like in this shtml-sample:

        <!--#include virtual="head.htm"-->
        <center><!-- cgi: head --><center>
        <!-- do: BLOCK_P -->
            <p><!-- val: content --></p>
        <!-- loop: BLOCK_P -->


No environment variables are used.


Please report them.




The usual warnings if it cannot read or write the files involved.


1.00 / 01.05.2006

Init version

See CHANGES file for details


See TODO file


Thanks to Dmitry Klimov for technical translating


Serz Minus (Lepenkov Sergey) <>


Copyright (C) 1998-2013 D&D Corporation. All Rights Reserved


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