views:

139

answers:

2

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.

+1  A: 

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 (e.g. 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

heeen
OK - the problem with the first two suggestions is that I want to maintain my constants in one place - my constants package.The "Compile Time Constant Folding" suggestion seems the best solution - as i can use my constants package. But can someone explain how one would do this in a Catalyst controller?
cubabit
For more details on Constants in TT have a look at: http://template-toolkit.org/docs/modules/Template/Namespace/Constants.html
draegtun
+3  A: 

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.

friedo
You could also use the `CONSTANTS` option instead of the `VARIABLES` option.
Brad Gilbert