5

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?

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Douglas Mauch
  • 859
  • 2
  • 7
  • 18

1 Answers1

10

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 => {} } }
Borodin
  • 126,100
  • 9
  • 70
  • 144
  • Where did this come from? I see no reference to TRACE_VARS or variables() in the documentation for Template::Context. But it does work. ??? – Douglas Mauch Apr 18 '13 at 20:49
  • @DouglasMauch: The `template` method from `Template::Context` returns a `Template::Document` object, so it's in the [documentation for `Template::Document`](https://metacpan.org/module/Template::Document). I used `Template::Context` so that I could set `TRACE_VARS`. – Borodin Apr 18 '13 at 22:45