Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Is there not a way to set variables within a Template between the time you call new() and the time you call process(). I am in a mod_perl environment, so my Template object is created once at initial startup. I have an init() method I call upon each request and I need to set several Template variables within this method. This init() method takes place long before the process() method on the Template object is invoked.

Looking through the Template docs, I am not seeing any $tt->param(foo => 'bar'); or anything similar. All I see is the VARIABLES/PRE_DEFINE keys you can pass to new() and the variable hash you pass in process(). Looking through Template's code, the variable stash ends up being handled via XS, so I can't determine how to hack the internals. Am I stuck simply setting my own global stash within init() and then including that stash in my call to process()?

Replies are listed 'Best First'.
•Re: Template Toolkit - Setting variables between new() and process()
by merlyn (Sage) on Feb 27, 2004 at 21:31 UTC

      Why thank you. I was on a wild goosechase in the Template modules. The closest I got to finding this method was a call to Template::Stash->load(), which incidentally was XS coded. Thanks again :)

Re: Template Toolkit - Setting variables between new() and process()
by perrin (Chancellor) on Feb 27, 2004 at 21:11 UTC
    The normal way to do things is to run some code that generates data, and then pass that data to process(). It sounds like you didn't realize this when you structured your program. You can always put the data in a temporary place like $r->pnotes() if you don't want to restructure your code.

      This is where things are slightly odd. My code is structured in such a way that all the data is generated and then passed to process(). This init() method is the exception. The data I need to set is simple stuff such as a "logged_in => 1" so I know which menus to print out in the template (ie: login/register for no login, settings/logout for logged in users). I do wonder why there is no way of doing $tt->param(logged_in => 1);. Sounds like it could be used plenty.

        Sounds like you could just return this data from init() instead of trying to add it to a template at that point. You probably shouldn't be coupling your init() method so closely with the templating API, in case you want to switch template modules at some point.

        It doesn't sound very useful to me to make the template object act as temporary storage, but you're welcome to subclass Template and add it if you really want it.