Search code examples
perlconstantscatalysttemplate-toolkit

How can I define constants in a Template Tookit template in a Catalyst app?


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.


Solution

  • 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.