Cataly...ew::TT(3pm)
πΈ Catalyst::View::TT β the manual page, but make it make sense πΈ
okay bestie, gather round β this is the user-contributed Perl doc for Catalyst::View::TT, living in your friendly neighbourhood Perl manual section 3pm (that's "library functions", iykyk). It's a long one so this is part 1 of 2. Buckle up, we're doing lore, config, and unicode drama. π
β¨ NAME β¨
Catalyst::View::TT β the Template View Class. It's giving "your Catalyst app but make it templates." π
β¨ SYNOPSIS β¨
First up, use the helper to create your View:
myapp_create.pl view Web TT
Then add custom configuration in View/Web.pm:
__PACKAGE__->config(
# any TT configuration items go here
TEMPLATE_EXTENSION => '.tt',
CATALYST_VAR => 'c',
TIMER => 0,
ENCODING => 'utf-8'
# Not set by default
PRE_PROCESS => 'config/main',
WRAPPER => 'site/wrapper',
render_die => 1, # Default for new apps, see render method docs
expose_methods => [qw/method_in_view_class/],
);
Next, add include path configuration in MyApp.pm:
__PACKAGE__->config(
'View::Web' => {
INCLUDE_PATH => [
__PACKAGE__->path_to( 'root', 'src' ),
__PACKAGE__->path_to( 'root', 'lib' ),
],
},
);
Then render the view from lib/MyApp.pm or lib/MyApp::Controller::SomeController.pm:
sub message : Global {
my ( $self, $c ) = @_;
$c->stash->{template} = 'message.tt2';
$c->stash->{message} = 'Hello World!';
$c->forward( $c->view('Web') );
}
And access variables from the template:
The message is: [% message %].
# example when CATALYST_VAR is set to 'Catalyst'
Context is [% Catalyst %]
The base is [% Catalyst.req.base %]
The name is [% Catalyst.config.name %]
# example when CATALYST_VAR isn't set
Context is [% c %]
The base is [% base %]
The name is [% name %]
β¨ DESCRIPTION β¨
So this is the Catalyst view class for the Template Toolkit, bestie. Your application should define a view class which is a subclass of this module. Throughout this whole manual, it's assumed your app is named MyApp and you're creating a TT view named Web β these are just placeholders, swap them for whatever names you actually picked. fr fr
The easiest way to create a TT view class is through the myapp_create.pl script that gets created along with the application:
$ script/myapp_create.pl view Web TT
That creates a MyApp::View::Web.pm module in the lib directory (again, replace MyApp with your app's actual name) which looks something like this:
package FooBar::View::Web;
use Moose;
extends 'Catalyst::View::TT';
__PACKAGE__->config(DEBUG => 'all');
Now you can modify your action handlers in the main application and/or controllers to forward to your view class. You might choose to do this in the end() method, for example, to automatically forward all actions to the TT view class:
# In MyApp or MyApp::Controller::SomeController
sub end : Private {
my( $self, $c ) = @_;
$c->forward( $c->view('Web') );
}
But if you're using the standard auto-generated end action, you don't even need to do this! iconic
# in MyApp::Controller::Root
sub end : ActionClass('RenderView') {} # no need to change this line
# in MyApp.pm
__PACKAGE__->config(
...
default_view => 'Web',
);
This will Just Work. And it has the advantages that:
- If you want to use a different view for a given request, just set
$c->stash->{current_view}. (See Catalyst's$c->viewmethod for details. $c->res->redirectis handled by default. If you just forward toView::Webin yourendroutine, you could break this by sending additional content.
See Catalyst::Action::RenderView for more details.
π§ CONFIGURATION π§
There are a three different ways to configure your view class. The first way is to call the config() method in the view subclass. This happens when the module is first loaded.
package MyApp::View::Web;
use Moose;
extends 'Catalyst::View::TT';
__PACKAGE__->config({
PRE_PROCESS => 'config/main',
WRAPPER => 'site/wrapper',
});
You may also override the configuration provided in the view class by adding a View::Web section to your application config.
This should generally be used to inject the include paths into the view to avoid the view trying to load the application to resolve paths. smart move, honestly
.. inside MyApp.pm ..
__PACKAGE__->config(
'View::Web' => {
INCLUDE_PATH => [
__PACKAGE__->path_to( 'root', 'templates', 'lib' ),
__PACKAGE__->path_to( 'root', 'templates', 'src' ),
],
},
);
You can also configure your view from within your config file if you're using Catalyst::Plugin::ConfigLoader. This should be reserved for deployment-specific concerns. For example:
# MyApp_local.conf (Config::General format)
<View Web>
WRAPPER "custom_wrapper"
INCLUDE_PATH __path_to('root/templates/custom_site')__
INCLUDE_PATH __path_to('root/templates')__
</View>
might be used as part of a simple way to deploy different instances of the same application with different themes. π¦
π¦ DYNAMIC INCLUDE_PATH π¦
Sometimes it is desirable to modify INCLUDE_PATH for your templates at run time.
Additional paths can be added to the start of INCLUDE_PATH via the stash as follows:
$c->stash->{additional_template_paths} =
[$c->config->{root} . '/test_include_path'];
If you need to add paths to the end of INCLUDE_PATH, there is also an include_path() accessor available:
push( @{ $c->view('Web')->include_path }, qw/path/ );
WATCH OUT BESTIE. Note that if you useinclude_path()to add extra paths toINCLUDE_PATH, you MUST check for duplicate paths. Without such checking, the above code will addpathtoINCLUDE_PATHat every request, causing a memory leak. π
A safer approach is to use include_path() to overwrite the array of paths rather than adding to it. This eliminates both the need to perform duplicate checking and the chance of a memory leak:
@{ $c->view('Web')->include_path } = qw/path another_path/;
If you are calling render directly then you can specify dynamic paths by having a additional_template_paths key with a value of additional directories to search. See CAPTURING TEMPLATE OUTPUT for an example showing this.
π Unicode (pre Catalyst v5.90080) π
NOTE: Starting with Catalyst v5.90080 unicode and encoding has been baked into core, and the default encoding is UTF-8. The following advice is for older versions of Catalyst.
Be sure to set ENCODING => 'utf-8' and use Catalyst::Plugin::Unicode::Encoding if you want to use non-ascii characters (encoded as utf-8) in your templates. This is only needed if you actually have UTF8 literals in your templates and the BOM is not properly set. Setting encoding here does not magically encode your template output. If you are using this version of Catalyst you need to all the Unicode plugin, or upgrade (preferred)
π Unicode (Catalyst v5.90080+) π
This version of Catalyst will automatically encode your body output to UTF8. This means if your variables contain multibyte characters you don't need top do anything else to get UTF8 output. However if your templates contain UTF8 literals (like, multibyte characters actually in the template text), then you do need to either set the BOM mark on the template file or instruct TT to decode the templates at load time via the ENCODING configuration setting. Most of the time you can just do:
MyApp::View::HTML->config(
ENCODING => 'UTF-8');
and that will just take care of everything. This configuration setting will force Template to decode all files correctly, so that when you hit the finalize_encoding step we can properly encode the body as UTF8. If you fail to do this you will get double encoding issues in your output (but again, only for the UTF8 literals in your actual template text.) π
Again, this ENCODING configuration setting only instructs template toolkit how (and if) to decode the contents of your template files when reading them from disk. It has no other effect.
β RENDERING VIEWS β
The view plugin renders the template specified in the template item in the stash.
sub message : Global {
my ( $self, $c ) = @_;
$c->stash->{template} = 'message.tt2';
$c->forward( $c->view('Web') );
}
If a stash item isn't defined, then it instead uses the stringification of the action dispatched to (as defined by $c->action) β in the above example, this would be message, but because the default is to append .tt, it would load root/message.tt.
The items defined in the stash are passed to the Template Toolkit for use as template variables.
sub default : Private {
my ( $self, $c ) = @_;
$c->stash->{template} = 'message.tt2';
$c->stash->{message} = 'Hello World!';
$c->forward( $c->view('Web') );
}
A number of other template variables are also added:
c A reference to the context object, $c
base The URL base, from $c->req->base()
name The application name, from $c->config->{ name }
These can be accessed from the template in the usual way:
<message.tt2>:
The message is: [% message %]
The base is [% base %]
The name is [% name %]
The output generated by the template is stored in $c->response->body.
π CAPTURING TEMPLATE OUTPUT π
If you wish to use the output of a template for some other purpose than displaying in the response, e.g. for sending an email, this is possible using other views, such as Catalyst::View::Email::Template.
π₯ TEMPLATE PROFILING π₯
See the "TIMER" property of the config method. (Yes that's all it says. Go look, bestie.)
β¦and that's part 1! part 2 is coming, don't you dare close the tab π
β¨ METHODS β¨
okay bestie this is the good part, the actual methods you're gonna be calling π
πΈ new
The constructor for the TT view. It sets up the template provider, and it reads the application config. That's it, that's the whole vibe check. β¨
π process($c)
Renders whatever template is chillin' in $c->stash->{template} β or $c->action (the private name of the matched action) if the stash is empty. It calls render to do the actual rendering, and the output gets stored in $c->response->body. π
Fun fact: you can forward to the process method of a TT view from inside Catalyst, like this:
$c->forward('View::Web');
N.B. β this is usually done automatically by Catalyst::Action::RenderView, so like, you probably don't gotta do it by hand. π«Ά
π¦ render($c, $template, %args)
Renders the given template and returns the output. Throws a Template::Exception object upon error. Yes, throws. We'll get to that. π
The template variables get set to %$args if $args is a hashref, or to $c->stash otherwise. Either way, those variables get augmented with base set to $c->req->base, c set to $c, and name set to $c->config->{name}. Alternately β plot twist β the CATALYST_VAR configuration item can be defined to specify the name of a template variable through which the context reference ($c) can be accessed. In that case, the c, base, and name variables are omitted entirely.
$template can be anything that Template::process understands how to process, including the name of a template file or a reference to a test string. Peep Template::process for the full list of supported formats, bestie. π
Wanna use the render method outside of your Catalyst app? Just pass a undef context. Super useful for tests, for instance. π§
And you can also forward to the render method of a TT view from inside Catalyst to render page fragments, like this:
my $fragment = $c->forward("View::Web", "render", $template_name, $c->stash->{fragment_data});
π Backwards compatibility note
The render method used to just return the Template::Exception object, rather than just throwing it. That is now deprecated, and instead the render method will throw an exception for new applications. Legacy behaviour, beware.
This behaviour can be activated (and is activated in the default skeleton configuration) by using render_die => 1. If you rely on the legacy behaviour then a warning will be issued. π
To silence that warning, set render_die => 0, but it is recommended you adjust your code so that it works with render_die => 1. do it for your future self, queen
In a future release, render_die => 1 will become the default if unspecified. So like, get ahead of it. β°
π template_vars
Returns a list of keys/values to be used as the catalyst variables in the template. Simple, iconic, no notes. β¨
π config
This method lets your view subclass pass additional settings to the TT configuration hash β or to set the options as below. All the goodies live down here: π
β paths
The list of paths TT will look for templates in. That's it. That's the whole thing. π
πΈ expose_methods
The list of methods in your View class which should be made available to the templates.
For example:
expose_methods => [qw/uri_for_css/],
...
sub uri_for_css {
my ($self, $c, $filename) = @_;
# additional complexity like checking file exists here
return $c->uri_for('/static/css/' . $filename);
}
Then in the template:
[% uri_for_css('home.css') %]
look at her go π
π¦ content_type
This lets you override the default content type for the response. If you do not set this β and if you do not set the content type in your controllers β the default is text/html; charset=utf-8.
Use this if you're creating alternative view responses, such as text or JSON, and you want a global setting. β¨
Any content type set in your controllers before calling this view are respected and have priority. priority matters, bestie π
π "CATALYST_VAR"
Allows you to change the name of the Catalyst context object. If set, it will also remove the base and name aliases, so you will have access them through <context>. π
For example, if CATALYST_VAR has been set to Catalyst, a template might contain:
The base is [% Catalyst.req.base %]
The name is [% Catalyst.config.name %]
β± "TIMER"
If you have configured Catalyst for debug output, and turned on the TIMER setting, Catalyst::View::TT will enable profiling of template processing (using Template::Timer). This will embed HTML comments in the output from your templates, such as:
<!-- TIMER START: process mainmenu/mainmenu.ttml -->
<!-- TIMER START: include mainmenu/cssindex.tt -->
<!-- TIMER START: process mainmenu/cssindex.tt -->
<!-- TIMER END: process mainmenu/cssindex.tt (0.017279 seconds) -->
<!-- TIMER END: include mainmenu/cssindex.tt (0.017401 seconds) -->
....
<!-- TIMER END: process mainmenu/footer.tt (0.003016 seconds) -->
not the timestamps in your HTML, but honestly? slay. π₯
π "TEMPLATE_EXTENSION"
a suffix to add when looking for templates bases on the match method in Catalyst::Request. π
For example:
package MyApp::Controller::Test;
sub test : Local { .. }
Would by default look for a template in <root>/test/test. If you set TEMPLATE_EXTENSION to .tt, it will look for <root>/test/test.tt. π
π "PROVIDERS"
Allows you to specify the template providers that TT will use.
MyApp->config(
name => 'MyApp',
root => MyApp->path_to('root'),
'View::Web' => {
PROVIDERS => [
{
name => 'DBI',
args => {
DBI_DSN => 'dbi:DB2:books',
DBI_USER=> 'foo'
}
}, {
name => '_file_',
args => {}
}
]
},
);
The 'name' key should correspond to the class name of the provider you want to use. The _file_ name is a special case that represents the default TT file-based provider. By default the name will be prefixed with 'Template::Provider::'. You can fully qualify the name by using a unary plus:
name => '+MyApp::Provider::Foo'
You can also specify the 'copy_config' key as an arrayref, to copy those keys from the general config, into the config for the provider:
DEFAULT_ENCODING => 'utf-8',
PROVIDERS => [
{
name => 'Encoding',
copy_config => [qw(DEFAULT_ENCODING INCLUDE_PATH)]
}
]
This can prove useful when you want to use the additional_template_paths hack in your own provider, or if you need to use Template::Provider::Encoding. π§
π "CLASS"
Allows you to specify a custom class to use as the template class instead of Template.
package MyApp::View::Web;
use Moose;
extends 'Catalyst::View::TT';
use Template::AutoFilter;
__PACKAGE__->config({
CLASS => 'Template::AutoFilter',
});
This is useful if you want to use your own subclasses of Template, so you can, for example, prevent XSS by automatically filtering all output through | html. safety first, gorgeous π‘οΈ
π HELPERS
The Catalyst::Helper::View::TT and Catalyst::Helper::View::TTSite helper modules are provided to create your view module. They are invoked by the myapp_create.pl script:
$ script/myapp_create.pl view Web TT
$ script/myapp_create.pl view Web TTSite
The Catalyst::Helper::View::TT module creates a basic TT view module. The Catalyst::Helper::View::TTSite module goes a little further β it also creates a default set of templates to get you started, and it also configures the view module to locate the templates automatically. automatic? we love to see it. β¨
π NOTES
If you are using the CGI module inside your templates, you will experience that the Catalyst server appears to hang while rendering the web page. NOT a vibe. This is due to the debug mode of CGI (which is waiting for input in the terminal window). Turning off the debug mode using the -no_debug option solves the problem, eg.:
[% USE CGI('-no_debug') %]
crisis averted π
π«Ά SEE ALSO
Catalyst, Catalyst::Helper::View::TT, Catalyst::Helper::View::TTSite, Template::Manual
π AUTHORS
Sebastian Riedel, sri@cpan.org
Marcus Ramberg, mramberg@cpan.org
Jesse Sheidlower, jester@panix.com
Andy Wardley, abw@cpan.org
Luke Saunders, luke.saunders@gmail.com
legends, every single one of them π
π COPYRIGHT
This program is free software. You can redistribute it and/or modify it under the same terms as Perl itself.
and that's the whole page, bestie!! π this one came from perl v5.34.0 and it was dated 2022-08-06, filed under Cataly...ew::TT(3pm) β go forth and render some templates, you absolute icon π
β¨
π¦ where this page comes from
- debian bookworm: libcatalyst-view-tt-perl 0.46-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- debian trixie: libcatalyst-view-tt-perl 0.46-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libcatalyst-view-tt-perl 0.46-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu resolute: libcatalyst-view-tt-perl 0.46-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu stonking: libcatalyst-view-tt-perl 0.46-1 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms