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

Hello all,

I have a CGI::Application webapp in which I would like to dynamically include template file names based on context (specifically, which of several policies might apply to the end user).

Taking cues from the sources listed below, this seemed a trivial task; create a text substitution code reference and feed that to the filter option. However, I cannot get it to work, even after stripping down to the most basic test case.

Sources

My template test file (magic-tmpl.html):

<p>Where's the magic?</p> !!!blargle!!!

My test code:

#!/usr/bin/perl use Modern::Perl; use HTML::Template; # This is the part that would be context-driven, if it worked... my $policy_file = 'test-policy.html'; my $magic = sub { my $textref = shift; $textref =~ s/!!!blargle!!!/<tmpl_include $policy_file>/g; }; my $t = HTML::Template->new( filename => '/web/filter/data/magic-tmpl.html', filter => $magic ); say $t->output; __END__ Produces: <p>Where's the magic?</p> !!!blargle!!!

Obviously, the desired substitution is not occuring. If anyone can help me locate the appropriate fairy dust for this kind of magic, I should be very grateful. I am hoping for a solution within CGI::Application and HTML::Template, but would consider other frameworks as needed. Thank you for your time.

Replies are listed 'Best First'.
Re: Using the filter option of HTML::Template
by tangent (Parson) on Mar 11, 2016 at 15:18 UTC
    $textref is a scalar reference so you need to dereference it in the substitution:
    $$textref =~ s/!!!blargle!!!/<tmpl_include $policy_file>/g;
    Note the double '$$'
Re: Using the filter option of HTML::Template
by stevieb (Canon) on Mar 11, 2016 at 15:21 UTC

    The docs for HTML::Template states that "This subroutine will receive a single argument - a reference to a string containing the template file text." for the coderef you create for the filter param.

    So it looks like you're simply failing to use the scalar reference passed in, and essentially localizing the $textref var instead.

    Try changing:

    my $magic = sub { my $textref = shift; $textref =~ s/!!!blargle!!!/<tmpl_include $policy_file>/g; };

    To:

    my $magic = sub { my $textref = shift; # note the extra $ on the $textref var $$textref =~ s/!!!blargle!!!/<tmpl_include $policy_file>/g; };
Re: Using the filter option of HTML::Template
by perlfan (Parson) on Mar 12, 2016 at 00:32 UTC