abw / Template2

Perl Template Toolkit v2
http://template-toolkit.org/
146 stars 94 forks source link

Extracting META data #296

Closed randyl closed 2 years ago

randyl commented 2 years ago

It would be useful if there was an API to parse a template file just enough to extract the META data and make it available as a Perl hash. For example:

[% META foo = "bar", blech => 42 %]

Would be returned as this:

{ foo => "bar", blech => "42" }

This idea was mentioned on the mailing list a few years ago: https://groups.io/g/template-toolkit/topic/76325078#6.

abw commented 2 years ago

There isn't anything built-in but it's relatively easy to extract it. The template() method returns a Template::Document object which has the META items in it. You just need to ignore any items starting with _ and the name and modtime items.

my $template = Template->new->template('example.tt2');
my $meta = {
    map { $_ => $template->{ $_ } }
    grep { ! /^(_|name$|modtime$)/ }
    keys %$template
};
abw commented 2 years ago

On reflection I thought this was probably a useful thing to have built in. So I've added a meta() method to Template::Document. See the new t/meta.t test for an example: https://github.com/abw/Template2/blob/master/t/meta.t

abw commented 2 years ago

Closed as resolved.

randyl commented 2 years ago

Great, thank you!