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

Is there a way to extract the names of all mentioned variables in a template (Template::Toolkit)? Something like this:
my $config = {INTERPOLATE=>0, EVAL_PERL=>0}; my $template = Template->new($config); my $text = "[% var1 %] [% var2 %] [% var3 %]"; my $vars = $template->get_vars(\$text); # vars will contain ['var1', 'var2', 'var3']
Basically I'm putting translatable text in the template and I want to pull the translations from the database in one go instead of one by one.

Replies are listed 'Best First'.
Re: Template::Toolkit: get the names of mentioned variables?
by jasonk (Parson) on Apr 20, 2005 at 22:43 UTC

    Not really, there are so many legitimate variants that it's next to impossible to parse the template to determine what variables are going to be called (what do you do when you run up against var1.$var2.{$var3.$var4}.something?

    What I ended up doing when I needed to solve a similar problem was to override the Template::Stash object, with one that could determine the value to be put there at runtime. You may want to check the Class::DBI::Template::Stash subclass in my Class::DBI::Template module to see how I solved it.


    We're not surrounded, we're in a target-rich environment!

      Yeah, that's what I was afraid of. But since my template texts are currently very simple, for now I'm just going to do a regex parsing to extract the variables. Today's the deadline, argh!

      Thanks for the pointer, though. I'm just familiarizing with the various classes and I'll look into subclassing Template::Stash later. Seems like the proper thing to do. I'm thinking of processing the template twice, in the first pass my custom stash will remember the variable names.

        Well, subclassing Template::Stash is not hard at all after all. I just needed to supply a custom get() method. Works like a charm! I've accomplished what I needed to be done in the first place. Perl is great!