CGI::A...in::TT(3pm)

πŸ“¦
version 1.06+~cs1.3 Β· 5 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

🌸 NAME 🌸

CGI::Application::Plugin::TT β€” the plugin that adds Template Toolkit support to CGI::Application, and yes bestie it's iconic πŸ’…

πŸ¦‹ VERSION πŸ¦‹

version 1.06 ✨

πŸŽ€ 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 πŸ’–

Okay so CGI::Application::Plugin::TT brings the very popular Template Toolkit engine into your CGI::Application modules, and it does it by giving you a bunch of helper methods so you can process template files right from inside your runmodes. Slay.

It lowkey compliments the support for HTML::Template that's already built into CGI::Application through the load_tmpl method. But also it gives you a few extra features beyond just loading a template, iykyk πŸ¦‹


✨ 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 too β€” if you don't pass it, it gets autogenerated by a call to $self->tt_template_name. The return value is a scalar reference to the output of the template. No cap.

         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 is your lil control room: you use it to customize how CGI::Application::Plugin::TT works, and how the Template Toolkit module it wraps works. 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 that's 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. So like, don't do that πŸ’€

You don't have to call this method β€” the module works without any configuration. But most people will find it useful to set at least a path to where the template files live, 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, bestie:

πŸŽ€ TEMPLATE_OPTIONS πŸŽ€

This lets you customize how the Template object is created by giving a list of options that will be passed to the Template constructor. Peep the documentation for the Template module for the exact syntax of the parameters, or see below for an example.

πŸŽ€ TEMPLATE_NAME_GENERATOR πŸŽ€

This lets you provide your own method for auto-generating the template filename. It needs a reference to a function that will be passed the $self object as its only parameter. This function gets called every time $self->tt_process is called without giving the filename of the template to process. It can standardize the way templates are organized and structured by making template filenames follow a predefined pattern. So organized, so main character.

The default template filename generator uses the current module name and the name of the calling function to generate a filename. That means your templates are named by a combination of the module name and the runmode ✨

πŸŽ€ TEMPLATE_PRECOMPILE_DIR πŸŽ€

This option lets you specify a directory, or an array of directories, to search when this module is loaded, and then compile all files found into memory. It gives a speed boost in persistent environments (mod_perl, fast-cgi) and can improve memory usage in environments that use shared memory (mod_perl). Obsessed with efficiency, honestly πŸ”₯

πŸŽ€ TEMPLATE_PRECOMPILE_FILETEST πŸŽ€

This option lets you 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 returns the underlying Template Toolkit object that's used behind the scenes. It's usually not necessary to use this object directly, since you can process templates and configure the Template object through the tt_process and tt_config methods. Every call to this method returns the same object during a single request. It may be useful for debugging purposes though 🫢

🌈 tt_params 🌈

This method accepts a hash or hashref of parameters that will be included in the processing of every call to tt_process. Important note bestie: 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.

Every time 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 precedence 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 clears all the currently stored parameters that have been set with tt_params. Clean slate, periodt.

🧡 tt_pre_process 🧡

This is an overridable method that works in the spirit of cgiapp_prerun. It gets called just before a template is processed, and it 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 its 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 generates 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 lets you 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. We love a consistent queen πŸ‘‘

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 lets you 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 lets you 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. Important note: 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. No skipping, bestie 😭

         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 πŸ’…

okay so by default, the TT plugin is gonna automatically add a parameter called 'c' to the template that returns to your CGI::Application object $self. No cap. That means you can access any methods in your CGI::Application module that you’d normally call on $self from inside your template. It’s giving some powerful actions in your templates, fr fr. 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 responsibility as well. Bestie, be careful β€” 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 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 Perl code 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 built-in 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 source code 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 its 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 ✨

Here’s the singleton example in all its main-character glory:

         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' });
         }

πŸ’€ 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. Periodt.

πŸ‘€ SEE ALSO πŸ‘€

CGI::Application, Template, perl(1)

πŸ‘‘ AUTHOR πŸ‘‘

Cees Hek <cees@crtconsulting.ca>

This software is copyright (c) 2024 by Cees Hek.

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

πŸ’– That’s the whole vibe check, bestie β€” this page comes from perl v5.40.0 and is dated 2024-12-15. Go slay your templates. πŸ’…βœ¨

πŸ“¦ where this page comes from