I want to use a constant in my TT template. In HTML::Mason (my previous templating engine of choice) I could do:
<%once>
use MyApp::Constants qw(CONSTANT);
</%once>
How can I do this in Template Toolkit ? As mentioned in the title this is a Catalyst app so I was thinking I could put the constants in the stash but that seems a bit awkward.
--edit
Sorry - I should have mentioned I want to use my own constants - exported from MyApp::Constants, without duplication.
In your TT configuration, you can use the VARIABLES option to pass a list of values that will be passed to every template when it's processed. Using some symbol table trickery, you can suck out all your constants into the config:
use MyApp::Constants;
use Template;
my $tt; # template object
{
no strict 'refs';
$tt = Template->new( {
VARIABLES => { map { $_ => &{ 'MyApp::Constants::' . $_ } }
grep { defined &{ 'MyApp::Constants::' . $_ } }
keys %MyApp::Constants::
}
}
)
}
This looks at all the symbols in the package MyApp::Constants
, checks if they are defined as subroutines (this is what constant.pm
does under the hood) and then uses map
to provide a hashref of them to TT.
Several possibilities. Just define some variables:
[% users = {
tom => 'Thomas',
dick => 'Richard',
larry => 'Lawrence',
}
%]
[% FOREACH u IN users %]
* [% u.key %] : [% u.value %]
[% END %]
Use the global variable:
[% global.version=1.234 %]
This is Version [% global.version %].
The META directive allows simple metadata items to be defined within a template. These are evaluated when the template is parsed and as such may only contain simple values (eg it's not possible to interpolate other variables values into META variables).
[% META
title = 'The Cat in the Hat'
author = 'Dr. Seuss'
version = 1.23
%]
As you already mentioned in the question body, there's also this: http://template-toolkit.org/docs/manual/Variables.html#section_Compile_Time_Constant_Folding
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.