perltemplatesdancer

Perl - Template Toolkit - How get list of variables in the template?


I am using Perl with Dancer and Template::Toolkit.

I'm trying to create a generic routine that will be passed a template and the HTTP GET/POST parameters.

I need to find a way to get a list of the variables in the template, so I can retrieve them from the parameters, or return an error if one or more are missing.

I can go an ugly regex route, but I was hoping for a better/cleaner way.

All the templates are XML/SOAP with a few variables here and there.

Any ideas?


Solution

  • If you enable the TRACE_VARS option on the template context then you can use the variables method to get a hash of all the values accessed.

    This code shows a brief example

    use strict;
    use warnings;
    
    use Template::Context;
    use Data::Dump;
    
    my $template = '[% person.name %] <[% person.email %]>';
    
    my $context = Template::Context->new(TRACE_VARS => 1);
    my $compiled = $context->template(\$template) or die $context->error;
    my $variables = $compiled->variables;
    
    dd $variables;
    

    output

    { person => { email => {}, name => {} } }